/**
 * T9 · SPIFFE-ID scheme for per-host agent identity (INV4/INV14).
 * Form: `spiffe://relay.<domain>/account/<accountId>/host/<hostId>`.
 */
import type { SpiffeId } from '../types.js'
import { SpiffeIdSchema } from '../types.js'

export class SpiffeError extends Error {
  constructor(message: string) {
    super(message)
    this.name = 'SpiffeError'
  }
}

/** Trust domain from env (INV9 config), defaulting to a safe placeholder for local/dev. */
export function trustDomain(env: NodeJS.ProcessEnv = process.env): string {
  const d = env.RELAY_TRUST_DOMAIN
  return d !== undefined && d.length > 0 ? d : 'example.com'
}

export function spiffeIdFor(accountId: string, hostId: string, domain = trustDomain()): SpiffeId {
  if (accountId.length === 0 || hostId.length === 0) {
    throw new SpiffeError('accountId and hostId are required')
  }
  const id = `spiffe://relay.${domain}/account/${accountId}/host/${hostId}`
  return SpiffeIdSchema.parse(id)
}

const PARSE_RE =
  /^spiffe:\/\/relay\.[a-z0-9.-]+\/account\/([A-Za-z0-9_-]+)\/host\/([A-Za-z0-9_-]+)$/

export function parseSpiffeId(uri: SpiffeId): { accountId: string; hostId: string } {
  const parsed = SpiffeIdSchema.safeParse(uri) // rejects path-traversal / wildcard / malformed
  if (!parsed.success) throw new SpiffeError('invalid SPIFFE-ID (malformed / traversal / wildcard)')
  const m = PARSE_RE.exec(uri)
  if (m === null) throw new SpiffeError('unparseable SPIFFE-ID')
  return { accountId: m[1]!, hostId: m[2]! }
}
