import Foundation
import Observation

@MainActor
@Observable
final class DestinationsViewModel {

    // MARK: - State

    var routes: [Route] = []
    var isLoading: Bool = false
    var error: String?
    var selectedDate: Date

    // MARK: - Computed

    var filteredRoutes: [Route] {
        let month = Calendar.current.component(.month, from: selectedDate)
        return routes
            .filter { $0.availableIn(month: month) }
            .sorted { $0.destinationAirport.name.localizedCompare($1.destinationAirport.name) == .orderedAscending }
    }

    // MARK: - Private

    private let service: FlightService

    // MARK: - Init

    init(service: FlightService, date: Date) {
        self.service = service
        self.selectedDate = date
    }

    // MARK: - Loading

    func loadDestinations(airportId: String) async {
        isLoading = true
        error = nil

        do {
            let results = try await service.destinations(for: airportId)
            if !Task.isCancelled {
                routes = results
            }
        } catch {
            if !Task.isCancelled {
                self.error = error.localizedDescription
            }
        }

        if !Task.isCancelled {
            isLoading = false
        }
    }
}
