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

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

  const count = await prisma.purchase.count({
    where: {
      purchaseNo: {
        startsWith: prefix
      }
    }
  });

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