import Foundation

actor APIClient {
    private let vault: TokenVault
    init(vault: TokenVault) { self.vault = vault }

    func request(path: String, method: String = "GET", body: Data? = nil, idempotencyKey: String? = nil) async throws -> (Data, HTTPURLResponse) {
        let url = AppEnvironment.apiBaseURL.appending(path: path.trimmingCharacters(in: CharacterSet(charactersIn: "/")))
        var request = URLRequest(url: url)
        request.httpMethod = method
        request.timeoutInterval = 18
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("ios", forHTTPHeaderField: "X-Platform")
        if let token = vault.accessToken() { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }
        if let key = idempotencyKey { request.setValue(key, forHTTPHeaderField: "Idempotency-Key") }
        request.httpBody = body
        let (data, response) = try await URLSession.shared.data(for: request)
        guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }
        return (data, http)
    }
}

extension APIClient {
    func customerFavorites() async throws -> Data { try await request(path:"/customer/favorites", method:"GET") }
    func customerReviews() async throws -> Data { try await request(path:"/customer/reviews", method:"GET") }
    func customerProfile() async throws -> Data { try await request(path:"/customer/profile", method:"GET") }
}


extension APIClient {
    func providerDashboard() async throws -> Data { try await request(path:"/provider/dashboard").0 }
    func providerRequests() async throws -> Data { try await request(path:"/provider/requests").0 }
    func providerAppointments() async throws -> Data { try await request(path:"/provider/appointments").0 }
    func providerBranches() async throws -> Data { try await request(path:"/provider/branches").0 }
    func providerResources() async throws -> Data { try await request(path:"/provider/resources").0 }
    func providerMessages() async throws -> Data { try await request(path:"/provider/messages").0 }
}


extension APIClient {
    func providerLocation(_ body: Data) async throws -> Data { let (data, _) = try await request(path:"/provider/location",method:"POST",body:body); return data }
    func providerNavigation(requestId:Int) async throws -> Data { let (data, _) = try await request(path:"/provider/navigation?request_id=\(requestId)"); return data }
    func realtimeSync(requestId:Int, version:Int=0) async throws -> Data { let (data, _) = try await request(path:"/realtime/sync?request_id=\(requestId)&since_version=\(version)"); return data }
    func customerTracking(requestId:Int, version:Int=0) async throws -> Data { let (data, _) = try await request(path:"/customer/tracking?request_id=\(requestId)&since_version=\(version)"); return data }
}
