/**
 * T11 — control-plane bootstrap. Wires env → stores → services → Fastify routes. The runnable
 * v0.9-MVP default uses the in-memory stores; swapping in the Postgres/Redis-backed adapters
 * (db/pool.ts + db/migrations + an ioredis client) is the Testcontainers integration step (PLAN §10).
 *
 * CROSS-PACKAGE INTEGRATION POINTS (injected, not hard-imported):
 *   - `CapabilityVerifier` — P5 owns `verifyCapabilityToken` + the signing key. Injected here; the
 *     default stub REFUSES all tokens (fail-closed) until P5 is wired.
 *   - `RevocationBus` — publish side over Redis `relay:revocations` (P1 subscribes). Default is the
 *     in-memory bus for single-process dev.
 *   - `KmsResolver` — P5/§3.1 KMS custody of the CA intermediate key. Default is an in-process
 *     Ed25519 signer (DEV ONLY — NOT a real KMS).
 */
import Fastify, { type FastifyInstance } from 'fastify'
import { existsSync, readFileSync } from 'node:fs'
import type { ControlPlaneEnv } from './env.js'
import { createMemoryStores } from './store/memory.js'
import type { Stores, HostStore } from './store/ports.js'
import { createAuditLog } from './audit/log.js'
import { createAccountRegistry } from './registry/accounts.js'
import { createHostRegistry } from './registry/hosts.js'
import { createSessionRegistry } from './registry/sessions.js'
import { createSubdomainAssigner } from './subdomain/assign.js'
import { createPairingIssuer } from './pairing/issue.js'
import { createPairingRedeemer } from './pairing/redeem.js'
import { createNativeHostEnroller } from './pairing/native-redeem.js'
import { createLeafSigner, type LeafSigner } from './ca/sign.js'
import { loadRealLeafSigner } from './ca/issue.js'
import { createRoutingTable } from './routing/table.js'
import { createInMemoryRevocationBus, type TestableRevocationBus } from './routing/bus.js'
import { createMeteringCollector } from './metering/collect.js'
import { createDeprovisioner } from './deprovision/deprovision.js'
import { createAuthorizer, type CapabilityVerifier } from './api/authz.js'
import { buildRouter } from './api/provision.js'
import { buildCaSigner, inProcessCaSigner, type KmsResolver, type CaSigner } from './boot/ca-wiring.js'
import { configureCapabilityVerifyKey } from './boot/verifier.js'
import {
  createDeviceRegistry,
  createMemoryDeviceStore,
  type DeviceRegistry,
} from './registry/devices.js'
import { createFrpClientLeafSigner } from './ca/frpclient-issue.js'
import { createDeviceLeafSigner, type DeviceLeafSigner } from './ca/device-issue.js'
import { createLeafRenewer } from './ca/rotate.js'
import { buildDeviceEnrollRouter, type SubdomainOwnershipResolver } from './api/device-enroll.js'
import { buildAuthLoginRouter } from './api/auth-login.js'
import { loadEnrollSigningKey } from './boot/session-signing.js'
import type { LoginSeamConfig } from './auth/session.js'
import { buildRenewRouter } from './api/renew.js'
import { buildNativeCas, DEFAULT_NATIVE_DNS_ZONE, type NativeCas, type NativeCaMaterial } from './boot/native-ca.js'
import type { RevocationBus } from 'relay-contracts'

export interface ControlPlaneOverrides {
  readonly stores?: Stores
  readonly verifier?: CapabilityVerifier
  readonly bus?: RevocationBus & Partial<TestableRevocationBus>
  readonly kmsResolver?: KmsResolver
  readonly caChainDer?: readonly Uint8Array[]
  /** Production mode → native-CA + renew-anchor material is fail-closed (INV9). Defaults to NODE_ENV. */
  readonly production?: boolean
  /**
   * Pre-built native-tunnel CAs (A2-prep production path). When supplied, `buildControlPlane` uses
   * these verbatim and does NOT call `buildNativeCas` — this is how `server.ts` threads the two
   * on-disk P-256 CAs (`buildFileBackedNativeCas`) in without coupling them to the intermediate
   * `kmsResolver`. Takes precedence over `nativeCaMaterial`.
   */
  readonly nativeCas?: NativeCas
  /** Production-loaded native-tunnel CA material (per-CA KMS ref + public cert DER). */
  readonly nativeCaMaterial?: NativeCaMaterial
  /** DNS zone the native-tunnel leaves are stamped under (defaults to `terminal.yaojia.wang`). */
  readonly nativeDnsZone?: string
}

/** Native-tunnel PKI handles exposed for wiring + tests (the enroll/renew issuers behind the routes). */
export interface NativeTunnelHandles {
  readonly nativeCas: NativeCas
  /** Host frp-client P-256 leaf signer (used at onboarding to mint the first leaf). */
  readonly hostSigner: LeafSigner
  /** Device P-256 leaf signer (shares the device store with the registry + renew path). */
  readonly deviceSigner: DeviceLeafSigner
  /** Device registry (ownership + cap/rate + expiry-renewal source of truth). */
  readonly deviceRegistry: DeviceRegistry
}

export interface BuiltControlPlane {
  readonly app: FastifyInstance
  readonly stores: Stores
  readonly nativeTunnel: NativeTunnelHandles
}

/**
 * Default fail-closed verifier — refuses everything until a real (P5) verifier is injected (INV6).
 * Async-shaped to match `CapabilityVerifier`: an async body that throws rejects the promise, so the
 * authorizer's `await` surfaces it as a 401.
 */
const refuseAllVerifier: CapabilityVerifier = {
  async verify(): Promise<never> {
    throw new Error('capability verification not configured (P5 integration point)')
  },
}

/**
 * Choose the leaf signer. When the intermediate PRIVATE key file is present on disk, issue REAL
 * X.509 leaves (production); when absent, fall back to the dev placeholder signer so tests and
 * key-less dev boots still run. A present-but-unreadable/malformed key FAILS FAST (INV9).
 */
async function buildLeafSigner(
  env: ControlPlaneEnv,
  hosts: HostStore,
  caSigner: CaSigner,
  caChainDer: readonly Uint8Array[],
): Promise<LeafSigner> {
  if (!existsSync(env.caIntermediateKeyPath)) {
    return createLeafSigner({ hosts, signer: caSigner, caChainDer })
  }
  try {
    return await loadRealLeafSigner({
      hosts,
      intermediateKeyPem: readFileSync(env.caIntermediateKeyPath, 'utf8'),
      intermediateCertPem: readFileSync(env.caIntermediateCertPath, 'utf8'),
      rootCertPem: readFileSync(env.caRootCertPath, 'utf8'),
      trustDomain: env.relayTrustDomain,
    })
  } catch (err: unknown) {
    // Never echo key material — only that loading failed and which path shape was configured (INV9).
    throw new Error(
      `failed to load CA leaf-signing material: ${err instanceof Error ? err.message : 'unknown'}`,
    )
  }
}

/** In-process KMS resolver — DEV ONLY. Production injects a real non-exportable KMS key (§3.1). */
function devKmsResolver(): KmsResolver {
  const signer = inProcessCaSigner()
  return {
    async resolve() {
      return { signer, policyRestrictedToServicePrincipal: true }
    },
  }
}

export async function buildControlPlane(
  env: ControlPlaneEnv,
  overrides: ControlPlaneOverrides = {},
): Promise<BuiltControlPlane> {
  const stores = overrides.stores ?? createMemoryStores()
  const bus: RevocationBus = overrides.bus ?? createInMemoryRevocationBus()
  const caChainDer = overrides.caChainDer ?? []

  const audit = createAuditLog(stores.audit)
  const accounts = createAccountRegistry({ accounts: stores.accounts, audit })
  const hosts = createHostRegistry({ hosts: stores.hosts, audit })
  createSessionRegistry({ sessions: stores.sessions, hosts: stores.hosts })
  const subdomains = createSubdomainAssigner({ subdomains: stores.subdomains, audit })

  const caSigner = await buildCaSigner(env, overrides.kmsResolver ?? devKmsResolver())
  const leafSigner = await buildLeafSigner(env, stores.hosts, caSigner, caChainDer)

  const pairingIssuer = createPairingIssuer({ pairing: stores.pairing, pairingTtlSec: env.pairingTtlSec, audit })
  const redeemer = createPairingRedeemer({
    pairing: stores.pairing,
    hosts,
    subdomains,
    leafSigner,
    pairingMaxRedeemAttempts: env.pairingMaxRedeemAttempts,
    audit,
  })

  const routing = createRoutingTable({
    routes: stores.routes,
    nodeStatus: async (nodeId) => (await stores.nodes.get(nodeId))?.status ?? null,
  })
  createMeteringCollector({ metering: stores.metering, hosts })
  const deprovisioner = createDeprovisioner({ hosts, routing })
  void bus // reserved for the node-coordinator / revoker wiring (drain + revoke publishers)

  // A real (injected) verifier is P5's async `verifyCapabilityToken`, which reads its Ed25519 key
  // from relay-auth's startup registry — so load that key from env at boot. The fail-closed default
  // never reads a key, so leave relay-auth's registry untouched when nothing is injected (INV6).
  const verifier = overrides.verifier ?? refuseAllVerifier
  if (overrides.verifier !== undefined) {
    await configureCapabilityVerifyKey(env.capabilitySignPubkey)
  }

  const authorizer = createAuthorizer({
    verifier,
    expectedAud: env.baseDomain,
  })

  // ── Native-tunnel PKI: frp-client-CA (host) + device-CA (device), both P-256 (§1.3) ───────────────
  // Production is fail-closed: `buildNativeCas` refuses to boot without real KMS-backed material, and
  // the renew route MUST validate presented certs against non-empty anchors (renew.ts). DEV generates
  // self-signed in-process P-256 CAs so leaves chain to a real, re-parseable CA.
  const production = overrides.production ?? process.env.NODE_ENV === 'production'
  // `server.ts` builds the two on-disk P-256 CAs itself (buildFileBackedNativeCas, with the file
  // resolver) and threads them in as `nativeCas` — decoupled from the intermediate `kmsResolver`.
  const nativeCas =
    overrides.nativeCas ??
    (await buildNativeCas(env, {
      production,
      ...(overrides.kmsResolver !== undefined ? { kmsResolver: overrides.kmsResolver } : {}),
      ...(overrides.nativeCaMaterial !== undefined ? { material: overrides.nativeCaMaterial } : {}),
    }))
  const nativeDnsZone = overrides.nativeDnsZone ?? DEFAULT_NATIVE_DNS_ZONE

  // ONE DeviceStore shared across the device registry, the device signer, and the renew path so the
  // signer's gate + renew-expiry bump all see the device the enroll route just registered.
  const deviceStore = createMemoryDeviceStore()
  const deviceRegistry = createDeviceRegistry({ devices: deviceStore })

  const hostSigner = createFrpClientLeafSigner({
    hosts: stores.hosts,
    signer: nativeCas.frpClientCa.signer,
    issuerName: nativeCas.frpClientCa.issuerName,
    caChainDer: nativeCas.frpClientCa.anchorsDer,
    trustDomain: env.relayTrustDomain,
    dnsZone: nativeDnsZone,
  })
  // Native (EC-P256) `/enroll` arm: pairing-gated host onboarding that mints the FIRST frp-client leaf
  // (mirrors the Ed25519 relay redeemer, but issues a P-256 leaf under a SERVER-assigned subdomain and
  // returns no E2E-relay content secret — L-host-hcs). Shares the frp-client `hostSigner` above so the
  // enroll-issued leaf and the later /renew leaf are stamped by the SAME CA + subdomain.
  const nativeEnroller = createNativeHostEnroller({
    pairing: stores.pairing,
    hosts,
    subdomains,
    hostSigner,
    pairingMaxRedeemAttempts: env.pairingMaxRedeemAttempts,
    audit,
  })
  const deviceSigner = createDeviceLeafSigner({
    signer: nativeCas.deviceCa.signer,
    issuer: nativeCas.deviceCa.issuerName,
    caChainDer: nativeCas.deviceCa.anchorsDer,
    sanBaseDomain: nativeDnsZone,
    trustDomain: env.relayTrustDomain,
    devices: deviceStore,
  })
  const renewer = createLeafRenewer({ hostSigner, deviceSigner, deviceExpiry: deviceRegistry })

  // The device leaf's dNSName SAN is nginx :8470's single tenant boundary, so the enroll route must
  // NOT trust the client-supplied subdomain: resolve who OWNS it against the host-onboarding registry
  // (deny-by-default: unknown → null). Same source of truth as `HostStore.getBySubdomain(...)`.
  const ownership: SubdomainOwnershipResolver = {
    async ownerOfSubdomain(subdomain) {
      return (await hosts.getHostBySubdomain(subdomain))?.accountId ?? null
    },
  }

  // Fail-closed: the renew route validates presented certs against these anchors; in production they
  // MUST be non-empty (renew.ts: "production wiring MUST supply them"). Refuse to boot otherwise.
  if (production && (nativeCas.frpClientCa.anchorsDer.length === 0 || nativeCas.deviceCa.anchorsDer.length === 0)) {
    throw new Error('native-tunnel renew anchors must be non-empty in production (fail-closed) — refusing to boot')
  }

  const app = Fastify({ logger: false })
  await app.register(buildRouter({ authorizer, accounts, hosts, pairingIssuer, redeemer, deprovisioner, nativeEnroller }))
  // Device enrollment is bearer-gated by the SAME capability verifier seam the admin API uses.
  await app.register(buildDeviceEnrollRouter({ verifier, devices: deviceRegistry, signer: deviceSigner, ownership }))
  // B1 — operator login → device:enroll bearer mint. The route ALWAYS registers (so a phone client
  // gets a coherent response), but is FAIL-CLOSED (503) unless the operator triplet is env-configured
  // (env.ts cross-validates set-together-or-none). The bearer is signed with the PRIVATE half of
  // `CAPABILITY_SIGN_PUBKEY_B64` so it verifies on the same §4.3 path /device/enroll checks. INV9: the
  // signing key is imported non-exportable + sign-only; the operator secret is never logged.
  const enrollSigningKey =
    env.capabilitySignPrivkey !== undefined ? await loadEnrollSigningKey(env.capabilitySignPrivkey) : null
  const loginConfig: LoginSeamConfig =
    env.operatorPassword !== undefined && env.operatorAccountId !== undefined
      ? { operatorCredential: env.operatorPassword, accountId: env.operatorAccountId }
      : {}
  await app.register(buildAuthLoginRouter({ signingKey: enrollSigningKey, loginConfig }))
  // Leaf renewal is mTLS-authenticated (current client cert) — anchors chain-validate the presented cert.
  await app.register(
    buildRenewRouter({
      hosts,
      devices: deviceRegistry,
      renewer,
      hostCaAnchorsDer: nativeCas.frpClientCa.anchorsDer,
      deviceCaAnchorsDer: nativeCas.deviceCa.anchorsDer,
    }),
  )
  return { app, stores, nativeTunnel: { nativeCas, hostSigner, deviceSigner, deviceRegistry } }
}
