import { prisma } from '../db';

/** Atomically bump a named counter and return the next integer. */
export async function nextCounter(key: string): Promise<number> {
  const row = await prisma.idCounter.upsert({
    where: { key },
    create: { key, value: 1 },
    update: { value: { increment: 1 } },
  });
  return row.value;
}

export async function nextEmployeeCode(): Promise<string> {
  const n = await nextCounter('emp');
  return `EMP-${String(n).padStart(3, '0')}`;
}

export async function nextProjectHumanCode(): Promise<string> {
  const n = await nextCounter('prj');
  return `PRJ-${String(n).padStart(3, '0')}`;
}

/** Task human code: PROJECTCODE-NNN (e.g. ZPT-111) */
export async function nextTaskCode(projectCode: string): Promise<string> {
  const key = `task_${projectCode.toUpperCase()}`;
  const n = await nextCounter(key);
  return `${projectCode.toUpperCase()}-${String(n).padStart(3, '0')}`;
}

/** Bug human code: BUG-NNN */
export async function nextBugCode(): Promise<string> {
  const n = await nextCounter('bug');
  return `BUG-${String(n).padStart(3, '0')}`;
}

export async function nextClientCode(): Promise<string> {
  const n = await nextCounter('client');
  return `CLT-${String(n).padStart(3, '0')}`;
}
