import Foundation

/// ONU resources and operations.
@MainActor
final class ONURepository {
    private let client: APIClient
    init(client: APIClient) { self.client = client }

    // MARK: Lists

    func states(query: APIQuery = .empty) async throws -> [ONUStateDoc] {
        try await client.get(.onuStates, query: query, as: [ONUStateDoc].self)
    }

    /// Fetch every ONU state, paging through with the `next` cursor.
    func allStates() async throws -> [ONUStateDoc] {
        try await client.getAll(.onuStates, idOf: { $0.documentId })
    }

    func configs(query: APIQuery = .empty) async throws -> [ONUConfigDoc] {
        try await client.get(.onuConfigs, query: query, as: [ONUConfigDoc].self)
    }

    /// Map of ONU id → operator name. Uses a `projection` so only `ONU.Name`
    /// comes back — full ONU-CFG docs are ~30 KB each, the name is a few bytes.
    func nameMap() async throws -> [String: String] {
        var query = APIQuery()
        query.projection = ["ONU.Name": 1]
        let configs: [ONUConfigDoc] = try await client.getAll(.onuConfigs, baseQuery: query, idOf: { $0.documentId })
        return configs.reduce(into: [:]) { map, config in
            if let name = config.name, !name.isEmpty { map[config.id] = name }
        }
    }

    // MARK: Detail

    func state(id: String) async throws -> ONUStateDoc {
        try await client.get(.onuState(id: id), as: ONUStateDoc.self)
    }

    func config(id: String) async throws -> ONUConfigDoc {
        try await client.get(.onuConfig(id: id), as: ONUConfigDoc.self)
    }

    func stats(id: String, lastHours: Int = 24) async throws -> [StatSample] {
        try await client.get(.onuStats(id: id),
                             query: .window(lastHours: lastHours),
                             as: [StatSample].self)
    }

    func logs(id: String, lastHours: Int = 24) async throws -> [LogEntry] {
        try await client.get(.onuLogs(id: id),
                             query: .window(lastHours: lastHours),
                             as: [LogEntry].self)
    }

    func alarmHistory(id: String) async throws -> AlarmHistoryDoc {
        try await client.get(.onuAlarmHistory(id: id), as: AlarmHistoryDoc.self)
    }

    func alarmHistories(query: APIQuery = .empty) async throws -> [AlarmHistoryDoc] {
        try await client.get(.onuAlarmHistories, query: query, as: [AlarmHistoryDoc].self)
    }

    func cpeStates(query: APIQuery = .empty) async throws -> [CPEState] {
        try await client.get(.onuCPEStates, query: query, as: [CPEState].self)
    }

    /// Per-CPE DHCP/lease state from the web helper `/cpe/onu/<id>/`, which
    /// returns a bare `[code, cpe, …]` array. Returns the CPE objects.
    func cpes(id: String) async throws -> [CPEState] {
        let raw = try await client.getRaw(.onuCPE(id: id))
        guard let array = raw.arrayValue else { return [] }
        return array.compactMap { $0.objectValue != nil ? CPEState(raw: $0) : nil }
    }

    // MARK: Firmware

    func firmwareFiles() async throws -> [FirmwareFile] {
        try await client.get(.onuFirmwareFiles, as: [FirmwareFile].self)
    }

    /// Procedure 7: stage `file` in the ONU's inactive firmware bank via a
    /// full-document PUT. Returns the bank slot written. Service-affecting —
    /// gate behind an explicit confirmation.
    @discardableResult
    func upgradeFirmware(id: String, file: FirmwareFile) async throws -> Int {
        guard let filename = file.filename, let version = file.version else {
            throw APIError.encoding(message: "Firmware file is missing a filename or version.")
        }
        let config = try await config(id: id)
        guard let result = FirmwareUpgrade.apply(to: config.raw, filename: filename, version: version) else {
            throw APIError.encoding(message: "Unexpected ONU-CFG shape — firmware write aborted.")
        }
        try await putConfig(id: id, document: result.document)
        return result.slot
    }

    // MARK: Operations (consequential — gate behind confirm dialogs)

    /// `PUT /onus/<id>/reset/`
    func reset(id: String) async throws {
        let _: JSONValue = try await client.action("PUT", .onuReset(id: id), as: JSONValue.self)
    }

    /// `DELETE /onus/configs/<id>/`
    func delete(id: String) async throws {
        try await client.delete(.onuConfig(id: id))
    }

    /// GET-modify-PUT: upload a full replacement ONU-CFG document.
    /// Mutate the `raw` JSONValue from `config(id:)`, then pass it here.
    func putConfig(id: String, document: JSONValue) async throws {
        let _: JSONValue = try await client.send(
            "PUT", .onuConfig(id: id),
            body: document, wrapInData: true, as: JSONValue.self)
    }
}
