import { getAppSettings } from "@/lib/app-settings";
import { prisma } from "@/lib/prisma";

export async function generateReceiptNo(receiptDate: Date) {
  const y = receiptDate.getUTCFullYear().toString();
  const m = String(receiptDate.getUTCMonth() + 1).padStart(2, "0");
  const d = String(receiptDate.getUTCDate()).padStart(2, "0");
  const settings = await getAppSettings();
  const prefix = `${settings.receipt_prefix.toUpperCase()}-${y}${m}${d}`;

  const count = await prisma.receipt.count({
    where: {
      receiptNo: {
        startsWith: prefix
      }
    }
  });

  return `${prefix}-${String(count + 1).padStart(3, "0")}`;
}
