/**
 * Requisition code generator. Format: REQ-<id>, e.g. REQ-9000.
 *
 * The id is a globally sequential integer floored at 9000 (mirroring the PO
 * numbering convention in lib/po-number.ts) so generated codes never collide
 * with any future imported/historical numbering. Call inside the same
 * transaction that creates the requisition to minimise race windows.
 */

import { db } from "@/lib/db";
import type { Prisma } from "@prisma/client";

const PREFIX = "REQ-";
const FLOOR = 8999; // first generated id is 9000

/** Next sequential requisition id by scanning existing REQ- codes. */
async function nextRequisitionId(client: Prisma.TransactionClient | typeof db): Promise<number> {
  const rows = await client.requisition.findMany({ select: { code: true } });
  let maxId = FLOOR;
  for (const { code } of rows) {
    if (!code.startsWith(PREFIX)) continue;
    const n = parseInt(code.slice(PREFIX.length), 10);
    if (!isNaN(n) && n > maxId) maxId = n;
  }
  return maxId + 1;
}

/** Generate the next requisition code (e.g. "REQ-9000"). */
export async function generateRequisitionCode(
  client: Prisma.TransactionClient | typeof db = db
): Promise<string> {
  const id = await nextRequisitionId(client);
  return `${PREFIX}${id}`;
}
