package wang.yaojia.webterm.wiring

import dagger.Lazy
import wang.yaojia.webterm.api.routes.ApiClient
import wang.yaojia.webterm.wire.HostEndpoint
import wang.yaojia.webterm.wire.HttpTransport
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Builds an [ApiClient] bound to a specific [HostEndpoint] over the ONE shared [HttpTransport] (A15
 * wiring). [ApiClient] is per-host (it stamps `Origin` from its endpoint), so it cannot be a plain
 * singleton — this factory injects the shared transport once and mints a client per host on demand
 * (session list, projects, timeline, cert-gated probe, FCM registration).
 *
 * ### The transport is [Lazy] (FIX 3 — no AndroidKeyStore/Tink I/O on the injection/Main thread)
 * Resolving [HttpTransport] builds the shared `OkHttpClient` (which first-touches the mTLS material:
 * slow AndroidKeyStore + Tink I/O). A `dagger.Lazy<HttpTransport>` keeps constructing this factory (and
 * `AppEnvironment`) cheap; the heavy build happens off `Main` in [warm] (called from
 * `AppEnvironment.warmUp()` on `Dispatchers.IO`). `HttpTransport` and `TermTransport` share the SAME
 * client singleton, so warming either builds it once for both WS and REST.
 */
@Singleton
public class ApiClientFactory @Inject constructor(
    private val http: Lazy<HttpTransport>,
) {
    /**
     * Resolve the shared [HttpTransport] (→ builds the shared `OkHttpClient`) so the slow mTLS I/O runs
     * on the CALLER's thread. Call ONLY from a background dispatcher (`AppEnvironment.warmUp()`).
     */
    public fun warm() {
        http.get()
    }

    /** Resolves the [Lazy] transport; call [warm] off `Main` first so this is a cheap singleton read. */
    public fun create(endpoint: HostEndpoint): ApiClient = ApiClient(endpoint = endpoint, http = http.get())
}
