import Foundation

/// Builds and holds the networking stack for one MCMS connection. Construct this
/// once you have a host + trust policy, then hand the repositories to your view
/// models. Re-create it (or call `reset`) when the host/config changes.
@MainActor
final class MCMSConnection {
    let config: APIConfiguration
    let session: SessionStore
    let client: APIClient

    let auth: AuthRepository
    let onu: ONURepository
    let olt: OLTRepository
    let controller: ControllerRepository

    init(config: APIConfiguration) {
        self.config = config
        let session = SessionStore(config: config)
        let client = APIClient(config: config, session: session)
        self.session = session
        self.client = client
        self.auth = AuthRepository(client: client, session: session, config: config)
        self.onu = ONURepository(client: client)
        self.olt = OLTRepository(client: client)
        self.controller = ControllerRepository(client: client)
    }

    /// Fired when any request fails with 401/403 so the app can route back to
    /// login. Forwarded to the underlying `APIClient`.
    var onAuthExpired: (@MainActor () -> Void)? {
        get { client.onAuthExpired }
        set { client.onAuthExpired = newValue }
    }
}

/*
 USAGE SKETCH (delete once real views exist)

 // The appliance must present a CA-trusted cert (real cert, or an internal CA
 // installed on the device via MDM/profile) — system trust only, no self-signed bypass:
 let url = URL(string: "https://mcms.example.com/api")!
 let config = APIConfiguration(
     baseURL: url,
     apiVersion: "v1",                       // confirm /api/v1 vs /v1 from openapi.json
     databaseId: nil                         // or a specific DB id
 )                                            // trustPolicy defaults to .system

 let connection = MCMSConnection(config: config)

 // Login (creds pulled from Keychain in real code):
 try await connection.auth.login(email: email, password: password)

 // Dashboard data:
 let onus = try await connection.onu.allStates()
 let counts = Dictionary(grouping: onus, by: { $0.lifecycle }).mapValues(\.count)

 // ONU detail:
 let stats = try await connection.onu.stats(id: "BFWS00123193", lastHours: 24)

 // An operation (gate behind a confirm dialog):
 try await connection.onu.reset(id: "BFWS00123193")

 try await connection.auth.logout()
*/
