import Foundation
import UIKit

struct ApiError: LocalizedError { let status: Int; let message: String; var errorDescription: String? { message } }

/// CarePulse REST API v1 (same endpoints as the Android app and the edge gateway).
final class Api {
    let server: String
    let token: String?
    init(server: String, token: String?) { self.server = server.hasSuffix("/") ? String(server.dropLast()) : server; self.token = token }

    private func call(_ method: String, _ path: String, _ body: [String: Any]? = nil) async throws -> [String: Any] {
        var r = URLRequest(url: URL(string: server + path)!, timeoutInterval: 30)
        r.httpMethod = method
        r.setValue("application/json", forHTTPHeaderField: "Accept")
        if let t = token { r.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization") }
        if let b = body { r.setValue("application/json", forHTTPHeaderField: "Content-Type"); r.httpBody = try JSONSerialization.data(withJSONObject: b) }
        let (data, resp) = try await URLSession.shared.data(for: r)
        let code = (resp as? HTTPURLResponse)?.statusCode ?? 0
        let json = (try? JSONSerialization.jsonObject(with: data) as? [String: Any]) ?? [:]
        if code >= 400 && code != 422 { throw ApiError(status: code, message: json["error"] as? String ?? "Server error \(code)") }
        return json
    }

    /// Code like "SHIVA-123456" (typed or scanned from the hospital's QR) → token + config.
    static func pair(server: String, code: String) async throws -> [String: Any] {
        let api = Api(server: server, token: nil)
        let info = await MainActor.run { "iOS \(UIDevice.current.systemVersion) · \(UIDevice.current.model)" }
        return try await api.call("POST", "/api/v1/gateway/pair", ["code": code, "platform": "ios",
                                                                   "app_version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "3.0.0", "device_info": info])
    }
    func config() async throws -> [String: Any] { try await call("GET", "/api/v1/gateway/config") }
    func readings(_ batches: [[String: Any]]) async throws -> [String: Any] { try await call("POST", "/api/v1/readings", ["batches": batches]) }
    func heartbeat(_ body: [String: Any]) async throws { _ = try await call("POST", "/api/v1/gateway/heartbeat", body) }
    /// Today's medicine doses for the paired patient (Phase 5).
    func medications() async throws -> [[String: Any]] { (try await call("GET", "/api/v1/medications"))["doses"] as? [[String: Any]] ?? [] }
    /// type: "taken" | "skipped" | "puff"
    func dose(medicationId: Int, type: String, puffs: Int? = nil) async throws {
        var ev: [String: Any] = ["type": type, "medication_id": medicationId, "at": ISO8601DateFormatter().string(from: Date())]
        if let p = puffs { ev["puffs"] = p }
        let r = try await call("POST", "/api/v1/doses", ["events": [ev]])
        if r["ok"] as? Bool == false { throw ApiError(status: 422, message: r["error"] as? String ?? "Not saved") }
    }
}
