package wang.yaojia.webterm.hostregistry

import wang.yaojia.webterm.wire.HostEndpoint

/**
 * A paired web-terminal host (frozen contract, plan §3 :host-registry). Immutable
 * snapshot mirroring iOS `HostRegistry.Host`: identity ([id]) and dial info
 * ([endpoint]) are fixed at creation; "renaming" a host means upserting a NEW value
 * with the same [id] (see the `upserting`/`removing` transforms in HostStore.kt).
 *
 * - [id] is a stable UUID string, allocated once when the host is first paired.
 * - [endpoint] is the SINGLE point of Origin/WS derivation ([HostEndpoint], frozen
 *   in :wire-protocol) — never redeclared here. Persistence stores only the
 *   [HostEndpoint.baseUrl] string and reconstructs via [HostEndpoint.fromBaseUrl],
 *   re-validating on load (host records are untrusted at rest — see HostCodec).
 * - [hasDeviceCert] is a UI flag (does this host have an imported mTLS client
 *   identity?) surfaced by the session-list host menu / cert screen.
 */
public data class Host(
    val id: String,
    val name: String,
    val endpoint: HostEndpoint,
    val hasDeviceCert: Boolean = false,
) {
    public companion object {
        /**
         * Validating factory: reconstructs [endpoint] from an untrusted [baseUrl]
         * (QR/manual entry, or a value read back from storage). Returns null when
         * [baseUrl] is not a valid http(s) URL — the caller drops the record rather
         * than trusting a malformed endpoint at rest.
         */
        public fun create(
            id: String,
            name: String,
            baseUrl: String,
            hasDeviceCert: Boolean = false,
        ): Host? {
            val endpoint = HostEndpoint.fromBaseUrl(baseUrl) ?: return null
            return Host(id = id, name = name, endpoint = endpoint, hasDeviceCert = hasDeviceCert)
        }
    }
}
