// composables/useRegionFlights.ts
import {computed, Ref} from "vue";
import {Flight, Region} from "@/Types/types";

export function useRegionFlights(
    flights: Ref<Flight[]>,
    regionCodes: string[],
    countryCode: string,
    regions: Ref<Region[]>,
) {
    const filteredFlights = computed(() => {
        return flights.value.filter(flight => {
            const depCode = flight.departure_airport?.region?.local_code
            const depCountry = flight.departure_airport?.region?.country?.code
            const arrCode = flight.arrival_airport?.region?.local_code
            const arrCountry = flight.arrival_airport?.region?.country?.code

            return (depCountry === countryCode && depCode && regionCodes.includes(depCode)) ||
                (arrCountry === countryCode && arrCode && regionCodes.includes(arrCode))
        })
    })

    const flightsByRegion = computed(() => {
        const grouped = filteredFlights.value.reduce((grouped, flight) => {
            const dep = flight.departure_airport?.region
            const arr = flight.arrival_airport?.region

            const regions = [
                    dep?.country?.code === countryCode ? dep?.local_code : null,
                    arr?.country?.code === countryCode ? arr?.local_code : null,
                ].filter((code): code is string => !!code && regionCodes.includes(code))

            ;[...new Set(regions)].forEach(code => {
                if (!grouped[code]) grouped[code] = []
                grouped[code].push(flight)
            })

            return grouped
        }, {} as Record<string, Flight[]>)

        return Object.fromEntries(
            Object.entries(grouped).sort(([codeA], [codeB]) => {
                const nameA = regionNames.value[codeA] ?? codeA
                const nameB = regionNames.value[codeB] ?? codeB
                return nameA.localeCompare(nameB)
            })
        )
    })

    const regionNames = computed(() => {
        return Object.fromEntries(
            regions.value
                .filter(r => regionCodes.includes(r.local_code))
                .map(r => [r.local_code, r.name])
        )
    })

    const visitedRegions = computed(() => new Set(Object.keys(flightsByRegion.value)))

    return { filteredFlights, flightsByRegion, visitedRegions, regionNames }
}
