import Foundation

/// Connection configuration for the MCMS REST API.
///
/// This is intentionally URL-driven so the same build works whether you hit the
/// PON Controller **directly** or through a **reverse proxy** — the only thing
/// that changes is `baseURL` (and possibly `refererOverride` / cookie names).
///
/// Direct example:   `https://10.2.10.29/api`
/// Proxy example:     `https://mcms.internal.example.com`   (proxy forwards to /api)
///
/// NOTE: confirm the exact prefix (`/api/v1` vs `/v1`) against the shipped
/// `openapi.json` before shipping. `apiVersion` is applied per-request by the
/// endpoint builder, so it is kept separate from `baseURL`.
struct APIConfiguration: Equatable, Codable {

    /// Scheme + host (+ optional port) + any fixed path prefix, WITHOUT the
    /// version segment. e.g. `https://10.2.10.29/api`
    var baseURL: URL

    /// API version segment inserted after `baseURL`. Endpoints are versioned
    /// independently; default to v1 and override per-call where needed.
    var apiVersion: String = "v1"

    /// The MCMS database to select for the session (optional). When non-nil the
    /// client issues `PUT /v{n}/databases/selection/` after login.
    var databaseId: String?

    /// Value sent in the `Referer` header. The API uses this to identify the
    /// calling client. Defaults to `baseURL` when nil. Behind a proxy you may
    /// need to set this to the proxy's public origin.
    var refererOverride: String?

    /// Cookie names returned by the server on login. These match a standard
    /// Django/DRF backend, which is what the CSRF + `Referer` requirements
    /// imply — but verify against a real login response and override if needed.
    var sessionCookieName: String = "sessionid"
    var csrfCookieName: String = "csrftoken"

    /// How to treat the server's TLS certificate. Defaults to system trust; the
    /// app has no self-signed bypass, so a self-signed box needs its CA installed
    /// on the device (MDM/profile). See `ServerTrustEvaluator`.
    var trustPolicy: ServerTrustPolicy = .system

    /// Request timeout (seconds).
    var timeout: TimeInterval = 30

    init(
        baseURL: URL,
        apiVersion: String = "v1",
        databaseId: String? = nil,
        refererOverride: String? = nil,
        trustPolicy: ServerTrustPolicy = .system
    ) {
        self.baseURL = baseURL
        self.apiVersion = apiVersion
        self.databaseId = databaseId
        self.refererOverride = refererOverride
        self.trustPolicy = trustPolicy
    }

    /// The value to send in the `Referer` header.
    var refererValue: String {
        refererOverride ?? baseURL.absoluteString
    }

    /// Host used for trust pinning / cookie scoping.
    var host: String { baseURL.host ?? "" }
}
