import { sql } from 'drizzle-orm'; import { formatId, type IdNamespace } from '@cancerindex/shared'; import type { Database } from './client.js'; /** * Mint stable public identifiers from per-namespace counters (CLAUDE.md ยง6). * Atomic upsert-increment; `count` ids are reserved in one round trip. */ export async function mintIds(db: Database, ns: IdNamespace, count = 1): Promise { if (count < 1) return []; const rows = await db.execute<{ next: string | number }>(sql` INSERT INTO id_sequences (namespace, next) VALUES (${ns}, ${count + 1}) ON CONFLICT (namespace) DO UPDATE SET next = id_sequences.next + ${count} RETURNING next `); const next = Number(rows[0]?.next ?? 0); const first = next - count; return Array.from({ length: count }, (_, i) => formatId(ns, first + i)); } export async function mintId(db: Database, ns: IdNamespace): Promise { const [id] = await mintIds(db, ns, 1); if (!id) throw new Error('mint failed'); return id; }