/**
 * T3 · Deny-by-default tenant authz core (INV1/INV3/INV6).
 *
 * The ONLY authorization path. There is NO `allow-if-unspecified` branch: the function returns 403
 * unless every check passes. A host is resolved ONLY by a registry lookup keyed on the
 * token-scoped `host_id` (never by raw addr/hostname). `account_id` comes from the token's
 * authenticated `sub` (via `accountIdFromToken`) and `host.accountId` from the registry — never a
 * client field. Single-use consumption is done by T12 AFTER a full allow, so T3 stays pure.
 */
import type { CapabilityRight, CapabilityToken } from 'relay-contracts'
import type {
  AuthenticatedPrincipal,
  HostRegistryPort,
  SessionRegistryPort,
  RevocationStore,
} from '../types.js'
import { verifyCapabilityToken, verifyDpopProof, type DpopContext } from '../capability/verify.js'
import { accountIdFromToken, principalFromToken } from './principal.js'

export type AuthzOutcome =
  | {
      readonly ok: true
      readonly principal: AuthenticatedPrincipal
      readonly hostId: string
      readonly jti: string
    }
  | { readonly ok: false; readonly status: 401 | 403; readonly reason: string }

export interface ConnectRequest {
  readonly capabilityRaw: string
  readonly expectedAud: string
  readonly requestedHostId: string
  readonly requiredRight: CapabilityRight
}
export interface ReattachRequest extends ConnectRequest {
  readonly sessionId: string
}

function deny(status: 401 | 403, reason: string): AuthzOutcome {
  return { ok: false, status, reason }
}

/** Verify token + DPoP + revocation + rights + single-host + cross-tenant gate. Shared core. */
async function coreAuthorize(
  req: ConnectRequest,
  dpop: DpopContext,
  hosts: HostRegistryPort,
  revocation: RevocationStore,
  now: number,
): Promise<{ outcome: AuthzOutcome; accountId?: string; token?: CapabilityToken }> {
  let token: CapabilityToken
  try {
    token = await verifyCapabilityToken(req.capabilityRaw, req.expectedAud, now)
  } catch {
    return { outcome: deny(401, 'invalid_capability_token') }
  }
  // verifyDpopProof is fail-safe, but guard defensively so an unexpected throw becomes a single
  // audited deny (emitted once by onUpgrade) rather than an unhandled exception (Finding-4).
  try {
    if (!(await verifyDpopProof(token, dpop, now))) {
      return { outcome: deny(401, 'dpop_proof_failed') }
    }
  } catch {
    return { outcome: deny(401, 'dpop_proof_failed') }
  }
  if (await revocation.isRevoked(token.jti)) return { outcome: deny(403, 'token_revoked') }
  if (!token.rights.includes(req.requiredRight)) return { outcome: deny(403, 'insufficient_rights') }
  if (token.host !== req.requestedHostId) return { outcome: deny(403, 'host_scope_mismatch') }

  const host = await hosts.getById(req.requestedHostId)
  if (host === null) return { outcome: deny(403, 'unknown_host') }
  if (host.status === 'revoked') return { outcome: deny(403, 'host_revoked') }

  const tokenAccountId = accountIdFromToken(token) // == token.sub == principal.accountId
  if (host.accountId !== tokenAccountId) {
    return { outcome: deny(403, 'cross_tenant'), accountId: tokenAccountId, token } // THE INV1 gate
  }
  return {
    outcome: { ok: true, principal: principalFromToken(token), hostId: host.hostId, jti: token.jti },
    accountId: tokenAccountId,
    token,
  }
}

export async function authorizeConnect(
  req: ConnectRequest,
  dpop: DpopContext,
  hosts: HostRegistryPort,
  revocation: RevocationStore,
  now: number,
): Promise<AuthzOutcome> {
  return (await coreAuthorize(req, dpop, hosts, revocation, now)).outcome
}

export async function authorizeReattach(
  req: ReattachRequest,
  dpop: DpopContext,
  hosts: HostRegistryPort,
  sessions: SessionRegistryPort,
  revocation: RevocationStore,
  now: number,
): Promise<AuthzOutcome> {
  const base = await coreAuthorize(req, dpop, hosts, revocation, now)
  if (!base.outcome.ok) return base.outcome
  // INV6 re-validate: session must exist AND belong to the same account.
  const session = await sessions.getById(req.sessionId)
  if (session === null || session.accountId !== base.accountId) {
    return deny(403, 'cross_tenant_session')
  }
  return base.outcome
}
