import Alamofire
import Foundation
import LilithAgentCore
import LilithLogging
import MacSyncShared
import SwiftyJSON

private let log = AppLogger.logger(for: "ICalls.API")

// MARK: - Payload Types

public struct SyncCallPayload: Sendable {
    public let uniqueId: String
    public let address: String?
    public let normalizedAddress: String?
    public let contactName: String?
    public let direction: String
    public let callType: String
    public let answered: Bool
    public let durationSeconds: Double
    public let startedAt: String
    public let serviceProvider: String?

    var dictionary: [String: Any?] {
        [
            "uniqueId": uniqueId,
            "address": address,
            "normalizedAddress": normalizedAddress,
            "contactName": contactName,
            "direction": direction,
            "callType": callType,
            "answered": answered,
            "durationSeconds": durationSeconds,
            "startedAt": startedAt,
            "serviceProvider": serviceProvider,
        ]
    }
}

public struct ICallsStatsResponse {
    public let totalCalls: Int
    public let lastSyncAt: Date?
}

// MARK: - Protocol

public protocol ICallsAPIClientProtocol: AnyObject, Sendable {
    var isAuthenticated: Bool { get }
    func syncCalls(_ payloads: [SyncCallPayload]) async throws -> Int
    func getStats() async throws -> ICallsStatsResponse
}

// MARK: - APIClient

public final class APIClient: BaseAPIClient, ICallsAPIClientProtocol, @unchecked Sendable {
    public static let shared: APIClient = {
        APIClient(baseURL: macSyncResolveServerURL(), keychain: macSyncSharedKeychain)
    }()

    public var isAuthenticated: Bool {
        (try? getAuthToken()) != nil
    }

    // MARK: - Call Sync (read-only ingest)

    public func syncCalls(_ payloads: [SyncCallPayload]) async throws -> Int {
        let params: [String: Any] = ["calls": payloads.map { $0.dictionary }]
        let data = try await authenticatedRequest("/client/icalls/sync", method: .post, parameters: params)
        let json = JSON(data)
        guard json["success"].boolValue else {
            let msg = json["error"]["message"].stringValue
            throw APIError.serverError(statusCode: json["statusCode"].intValue,
                                       message: msg.isEmpty ? "Server error" : msg)
        }
        let synced = json["data"]["synced"].intValue
        log.info("syncCalls success synced=\(synced)")
        return synced
    }

    // MARK: - Stats

    public func getStats() async throws -> ICallsStatsResponse {
        let data = try await authenticatedRequest("/client/icalls/stats", method: .get)
        let json = JSON(data)
        guard json["success"].boolValue else {
            throw APIError.serverError(statusCode: 0, message: json["error"]["message"].stringValue)
        }
        return ICallsStatsResponse(
            totalCalls: json["data"]["totalCalls"].intValue,
            lastSyncAt: json["data"]["lastSyncAt"].string.flatMap { ISO8601DateFormatter().date(from: $0) }
        )
    }
}
