import path from "node:path";

import XLSX from "xlsx";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

const sourcePath =
  process.argv[2] ?? "/Users/wirabasalamah/work/abelbirdnest/data gudang/Grade.xls";

function formatCode(prefix, sequence) {
  return `${prefix}${String(sequence).padStart(5, "0")}`;
}

async function main() {
  const workbook = XLSX.readFile(sourcePath);
  const sheetName = workbook.SheetNames[0];
  const rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { defval: "" });

  let mangkokSequence = 1;
  let nonMangkokSequence = 1;

  for (const row of rows) {
    const legacyCode = String(row.Code || "").trim();
    const name = String(row.Name || "").trim();
    const description = String(row.Description || "").trim();
    const isMangkok = String(row.Mangkok || "").trim().toLowerCase() === "yes";

    if (!name) continue;

    const prefix = isMangkok ? "MGK" : "GRD";
    const code = isMangkok
      ? formatCode(prefix, mangkokSequence++)
      : formatCode(prefix, nonMangkokSequence++);

    await prisma.grade.upsert({
      where: { legacyCode: legacyCode || "__missing__" },
      update: {
        code,
        isMangkok,
        name,
        description: description || null,
        status: "ACTIVE"
      },
      create: {
        code,
        legacyCode: legacyCode || null,
        isMangkok,
        name,
        description: description || null,
        status: "ACTIVE"
      }
    });
  }

  const count = await prisma.grade.count();
  console.log(`Seeded grades: ${count} from ${path.basename(sourcePath)}`);
}

main()
  .catch((error) => {
    console.error(error);
    process.exitCode = 1;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
