import type { MutationCtx } from "../_generated/server";
import { SEQUENCES, type SequenceName } from "../../src/lib/sequence-defs";

/** Atomically produce the next human-readable reference (RES-1042, CUS-0184…). Runs inside the mutation's transaction. */
export async function nextCode(ctx: MutationCtx, name: SequenceName): Promise<string> {
  const cfg = SEQUENCES[name];
  const row = await ctx.db.query("sequences").withIndex("by_name", (q) => q.eq("name", name)).unique();
  const value = (row?.value ?? cfg.start) + 1;
  if (row) await ctx.db.patch(row._id, { value });
  else await ctx.db.insert("sequences", { name, value });
  return `${cfg.prefix}-${String(value).padStart(cfg.pad, "0")}`;
}
