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

export async function generateLotCode(receivedAt: Date, sourceCode?: string | null) {
  const yy = String(receivedAt.getUTCFullYear()).slice(-2);
  const mm = String(receivedAt.getUTCMonth() + 1).padStart(2, "0");
  const dd = String(receivedAt.getUTCDate()).padStart(2, "0");
  const normalizedSource = (sourceCode ?? "").replace(/[^a-zA-Z0-9]/g, "").toUpperCase().slice(0, 4);
  const sourcePart = normalizedSource || "N/A";
  const settings = await getAppSettings();
  const prefix = `${settings.lot_prefix.toUpperCase()}-${yy}${mm}${dd}-${sourcePart}`;

  const count = await prisma.inventoryLot.count({
    where: {
      lotCode: {
        startsWith: prefix
      }
    }
  });

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