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

export async function generateTransformationLotCode(
  transformationDate: Date,
  transformationType: string,
  offset = 0
) {
  const yy = String(transformationDate.getUTCFullYear()).slice(-2);
  const mm = String(transformationDate.getUTCMonth() + 1).padStart(2, "0");
  const dd = String(transformationDate.getUTCDate()).padStart(2, "0");
  const settings = await getAppSettings();
  const typeCode =
    transformationType.toUpperCase() === "REGRADE"
      ? "RGD"
      : settings.transformation_prefix.toUpperCase();
  const prefix = `${settings.lot_prefix.toUpperCase()}-${yy}${mm}${dd}-${typeCode}`;

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

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