/**
 * T5 — session registry. `account_id` is DENORMALIZED from the host at write time — NEVER
 * supplied by the caller/client (INV3) — giving an O(1) deny-by-default authz fact for reattach
 * (INV6). `sessionAccount` returns that server-derived owner; it never echoes a client value.
 */
import type { SessionRecord } from '../model/records.js'
import type { HostStore, SessionStore } from '../store/ports.js'
import { nowIso } from '../util/ids.js'

export interface RecordSessionInput {
  readonly sessionId: string
  readonly hostId: string
}

export interface SessionRegistry {
  recordSession(input: RecordSessionInput): Promise<SessionRecord>
  getSession(sessionId: string): Promise<SessionRecord | null>
  sessionAccount(sessionId: string): Promise<string | null>
}

export interface SessionRegistryDeps {
  readonly sessions: SessionStore
  readonly hosts: HostStore
}

export function createSessionRegistry(deps: SessionRegistryDeps): SessionRegistry {
  return {
    async recordSession(input) {
      const host = await deps.hosts.get(input.hostId)
      if (host === null) throw new Error('cannot record session for unknown host')
      const rec: SessionRecord = {
        sessionId: input.sessionId,
        hostId: input.hostId,
        accountId: host.accountId, // derived from the host — caller cannot influence (INV3)
        createdAt: nowIso(),
        lastAttachAt: nowIso(),
      }
      await deps.sessions.insert(rec)
      return rec
    },
    async getSession(sessionId) {
      return deps.sessions.get(sessionId)
    },
    async sessionAccount(sessionId) {
      const s = await deps.sessions.get(sessionId)
      return s?.accountId ?? null // O(1) authz fact; server-derived, never client-supplied
    },
  }
}
