import { computed, ComputedRef } from 'vue'
import { Flight } from '@/Types/types'

// ── Types ──────────────────────────────────────────────────────────────────

export interface AircraftFamilyEntry {
    family: string
    designators: string[]
    flights: Flight[]
}

// ── Composable ─────────────────────────────────────────────────────────────

export function useAircraftFamilies(
    flights: ComputedRef<Flight[]>,
    families: Record<string, string[]>,
) {
    // Build a lookup from designator → family name for O(1) matching
    const designatorToFamily = Object.entries(families).reduce<Record<string, string>>(
        (acc, [family, designators]) => {
            for (const d of designators) acc[d] = family
            return acc
        },
        {}
    )

    const entries = computed<AircraftFamilyEntry[]>(() => {
        // Pre-populate all families with empty flight lists
        const map = new Map<string, AircraftFamilyEntry>(
            Object.entries(families).map(([family, designators]) => [
                family,
                { family, designators, flights: [] },
            ])
        )

        for (const flight of flights.value) {
            const designator = flight.aircraft?.designator
            if (!designator) continue
            const family = designatorToFamily[designator]
            if (!family) continue
            map.get(family)!.flights.push(flight)
        }

        return [...map.values()]
    })

    const completedCount = computed(() => entries.value.filter(e => e.flights.length > 0).length)
    const totalCount = computed(() => entries.value.length)

    return { entries, completedCount, totalCount }
}
