import { PrismaClient } from "@prisma/client";
import { hash } from "bcryptjs";
import "dotenv/config";

const prisma = new PrismaClient();

async function main() {
  console.log("Seeding database...");

  // Create admin user
  const hashedPassword = await hash("admin123", 12);
  const admin = await prisma.user.upsert({
    where: { email: "admin@voter.local" },
    update: {},
    create: {
      name: "Administrator",
      email: "admin@voter.local",
      password: hashedPassword,
      role: "ADMIN",
    },
  });
  console.log("Created admin user:", admin.email);

  // Create sample area
  const area = await prisma.voterArea.upsert({
    where: { areaCode: "1048" },
    update: {},
    create: {
      areaCode: "1048",
      areaName: "টোলারবাগ",
      district: "ঢাকা",
      upazila: "মিরপুর",
      unionWard: "পল্লবী",
      postOffice: "মিরপুর",
    },
  });
  console.log("Created area:", area.areaName);

  // Create sample voter list
  const list = await prisma.voterList.upsert({
    where: { fileName: "sample-male-list" },
    update: {},
    create: {
      fileName: "sample-male-list",
      listType: "MALE",
      areaId: area.id,
      totalVoters: 2,
    },
  });
  console.log("Created voter list:", list.fileName);

  // Create sample voters
  const sampleVoters = [
    {
      entryNumber: 1,
      pageNumber: 1,
      voterNumber: "২৬১০৪৮০০২১১৮",
      name: "মোঃ জাকির হোসাইন",
      fatherName: "মোঃ সরুল হোসেন",
      motherName: "ফেরদৌস আরা বেগম",
      dateOfBirth: new Date("1998-09-24"),
      occupation: "ছাত্র/ছাত্রী",
      address: "টোলারবাগ, মিরপুর, ঢাকা",
    },
    {
      entryNumber: 2,
      pageNumber: 1,
      voterNumber: "২৬১০৪৮০০২১১৯",
      name: "মোঃ আসাদুজ্জামান নূর",
      fatherName: "মৃত নূরুজ্জামান মন্ডল",
      motherName: "ফাতেমা আক্তার",
      dateOfBirth: new Date("1997-07-02"),
      occupation: "ছাত্র/ছাত্রী",
      address: "টোলারবাগ, মিরপুর, ঢাকা",
    },
  ];

  for (const voter of sampleVoters) {
    await prisma.voter.upsert({
      where: {
        listId_entryNumber: {
          listId: list.id,
          entryNumber: voter.entryNumber,
        },
      },
      update: {},
      create: {
        ...voter,
        listId: list.id,
      },
    });
  }
  console.log(`Created ${sampleVoters.length} sample voters`);

  console.log("\nSeeding completed!");
  console.log("\nLogin credentials:");
  console.log("Email: admin@voter.local");
  console.log("Password: admin123");
}

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