/**
 * ids.ts — allocate the next human-readable ID for an investigation artefact.
 *
 * The id sequences in migration 0004 are atomic; nextval is concurrency-safe.
 * Padding is consistent across the wiki (CLAUDE.md naming regex).
 */
import { queryOne } from "./pg";

const PAD = 4;

async function nextval(seq: string, prefix: string): Promise<string> {
  const row = await queryOne<{ nextval: string }>(`SELECT nextval('${seq}') AS nextval`);
  const n = Number(row?.nextval ?? 1);
  return `${prefix}-${String(n).padStart(PAD, "0")}`;
}

export const allocate = {
  evidenceId:           () => nextval("public.evidence_id_seq",            "E"),
  hypothesisId:         () => nextval("public.hypothesis_id_seq",          "H"),
  contradictionId:      () => nextval("public.contradiction_id_seq",       "R"),
  witnessId:            () => nextval("public.witness_id_seq",             "W"),
  gapId:                () => nextval("public.gap_id_seq",                 "G"),
  residualUncertaintyId: () => nextval("public.residual_uncertainty_id_seq","RU"),
};
