import Foundation
import CoreLocation

final class RealtimeLocationManager: NSObject, CLLocationManagerDelegate {
    private let manager = CLLocationManager()
    private let api: APIClient
    private let queue: OfflineRetryQueue
    private var requestId: Int?

    init(api: APIClient, queue: OfflineRetryQueue) {
        self.api = api; self.queue = queue; super.init()
        manager.delegate = self; manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation; manager.distanceFilter = 5
    }

    func start(requestId:Int) { self.requestId = requestId; manager.requestWhenInUseAuthorization(); manager.startUpdatingLocation() }
    func stop() { manager.stopUpdatingLocation(); requestId = nil }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let id=requestId, let loc=locations.last else { return }
        let formatter=ISO8601DateFormatter()
        let dict:[String:Any] = [
            "request_id":id,"latitude":loc.coordinate.latitude,"longitude":loc.coordinate.longitude,
            "accuracy_m":max(0,loc.horizontalAccuracy),"speed_kmh":max(0,loc.speed*3.6),"heading_deg":max(0,loc.course),
            "client_recorded_at":formatter.string(from:loc.timestamp),"client_event_id":UUID().uuidString
        ]
        guard let body=try? JSONSerialization.data(withJSONObject:dict) else{return}
        Task {
            do { _ = try await api.request(path:"/provider/location",method:"POST",body:body) }
            catch { await queue.enqueue(path:"/provider/location",body:body) }
        }
    }
}
