import Foundation
import Observation

@Observable
@MainActor
final class FavoritesManager {
    private static let storageKey = "savedFavoriteRoutes"

    var favorites: [FavoriteRoute] = []

    init() {
        load()
    }

    func add(departure: Airport, arrival: Airport) {
        guard !isFavorite(departure: departure, arrival: arrival) else { return }
        let route = FavoriteRoute(departure: departure, arrival: arrival, addedDate: Date())
        favorites.append(route)
        save()
    }

    func remove(_ route: FavoriteRoute) {
        favorites.removeAll { $0.id == route.id }
        save()
    }

    func isFavorite(departure: Airport, arrival: Airport) -> Bool {
        favorites.contains { $0.departure.iata == departure.iata && $0.arrival.iata == arrival.iata }
    }

    func toggle(departure: Airport, arrival: Airport) {
        if isFavorite(departure: departure, arrival: arrival) {
            favorites.removeAll { $0.departure.iata == departure.iata && $0.arrival.iata == arrival.iata }
        } else {
            favorites.append(FavoriteRoute(departure: departure, arrival: arrival, addedDate: Date()))
        }
        save()
    }

    private func save() {
        guard let data = try? JSONEncoder().encode(favorites) else { return }
        UserDefaults.standard.set(data, forKey: Self.storageKey)
    }

    private func load() {
        guard let data = UserDefaults.standard.data(forKey: Self.storageKey),
              let decoded = try? JSONDecoder().decode([FavoriteRoute].self, from: data) else { return }
        favorites = decoded
    }
}
