import Foundation
import Observation
import CoreLocation

/// Asks CLLocationManager for the user's current location once. Used by
/// Wetter and Giftköder which need a position without the full tracking setup.
@Observable
@MainActor
final class OneShotLocation: NSObject, CLLocationManagerDelegate {
    private let manager = CLLocationManager()

    var coordinate: CLLocationCoordinate2D?
    var error: String?
    var isResolving: Bool = false

    override init() {
        super.init()
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyHundredMeters
    }

    func request() {
        error = nil
        isResolving = true
        switch manager.authorizationStatus {
        case .notDetermined:
            manager.requestWhenInUseAuthorization()
        case .denied, .restricted:
            error = "Standortzugriff verweigert."
            isResolving = false
        case .authorizedWhenInUse, .authorizedAlways:
            manager.requestLocation()
        @unknown default:
            error = "Unbekannter Standort-Status."
            isResolving = false
        }
    }

    nonisolated func locationManager(
        _ manager: CLLocationManager,
        didUpdateLocations locations: [CLLocation]
    ) {
        guard let loc = locations.first else { return }
        let c = loc.coordinate
        Task { @MainActor in
            self.coordinate = c
            self.isResolving = false
        }
    }

    nonisolated func locationManager(_ manager: CLLocationManager, didFailWithError err: Error) {
        let msg = err.localizedDescription
        Task { @MainActor in
            self.error = msg
            self.isResolving = false
        }
    }

    nonisolated func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        let status = manager.authorizationStatus
        Task { @MainActor in
            switch status {
            case .authorizedWhenInUse, .authorizedAlways:
                manager.requestLocation()
            case .denied, .restricted:
                self.error = "Standortzugriff verweigert."
                self.isResolving = false
            default:
                break
            }
        }
    }
}
