import { randomBytes, scryptSync } from "node:crypto";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

const roles = [
  { code: "ADMIN", name: "Administrator" },
  { code: "OWNER", name: "Owner" },
  { code: "PURCHASING", name: "Purchasing" },
  { code: "WAREHOUSE", name: "Warehouse" },
  { code: "QC", name: "Quality Control" },
  { code: "SALES", name: "Sales" },
  { code: "SYSTEM_ADMIN", name: "System Admin" }
];

function hashPassword(password) {
  const salt = randomBytes(16).toString("hex");
  const derived = scryptSync(password, salt, 64).toString("hex");
  return `${salt}:${derived}`;
}

async function main() {
  for (const role of roles) {
    await prisma.role.upsert({
      where: { code: role.code },
      update: { name: role.name },
      create: role
    });
  }

  const role = await prisma.role.findUniqueOrThrow({
    where: { code: "SYSTEM_ADMIN" }
  });

  await prisma.user.upsert({
    where: { email: "wirabasalamah@gmail.com" },
    update: {
      roleId: role.id,
      username: "wirabasalamah",
      name: "Wira Basalamah",
      passwordHash: hashPassword("password"),
      emailVerifiedAt: new Date(),
      status: "ACTIVE"
    },
    create: {
      roleId: role.id,
      username: "wirabasalamah",
      email: "wirabasalamah@gmail.com",
      name: "Wira Basalamah",
      passwordHash: hashPassword("password"),
      emailVerifiedAt: new Date(),
      status: "ACTIVE"
    }
  });
}

main()
  .then(async () => {
    console.log("Seeded SYSTEM_ADMIN user: wirabasalamah@gmail.com");
    await prisma.$disconnect();
  })
  .catch(async (error) => {
    console.error(error);
    await prisma.$disconnect();
    process.exit(1);
  });
