import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();

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

  // SECTION GROUPS
  console.log("Ensuring Section Groups...");
  const collegeSection = await prisma.sectionGroup.upsert({
    where: { name: "College Section" },
    update: {},
    create: { name: "College Section" },
  });
  const seniorSection = await prisma.sectionGroup.upsert({
    where: { name: "Senior Section" },
    update: {},
    create: { name: "Senior Section" },
  });

  // GRADE
  console.log("Ensuring Grades...");
  const grades = [];
  for (let i = 1; i <= 12; i++) {
    let sectionGroupId = null;
    if (i >= 11) sectionGroupId = collegeSection.id;
    else if (i >= 9) sectionGroupId = seniorSection.id;

    const grade = await prisma.grade.upsert({
      where: { level: i },
      update: { sectionGroupId },
      create: { level: i, sectionGroupId },
    });
    grades.push(grade);
  }

  // CLASSES (Sections)
  console.log("Ensuring Classes (Sections)...");

  const classDefinitions = [
    { level: 11, names: ["Engineering E1", "Computer C1", "Computer C2", "Medical M1"] },
    { level: 12, names: ["Engineering E1", "Computer Science", "Medical M1"] },
    { level: 9, names: ["A", "B", "C", "D", "E"] },
    { level: 10, names: ["A", "B", "C", "D", "E"] },
  ];

  // 1-8
  for (let i = 1; i <= 8; i++) {
    classDefinitions.push({ level: i, names: ["A"] });
  }

  for (const def of classDefinitions) {
    const grade = grades.find(g => g.level === def.level);
    if (grade) {
      for (const name of def.names) {
        // Check if class exists to avoid unique constraint error
        const existingClass = await prisma.class.findFirst({
          where: {
            name: name,
            gradeId: grade.id
          }
        });

        if (!existingClass) {
          await prisma.class.create({
            data: {
              name: name,
              gradeId: grade.id,
              capacity: 45, // Default capacity
            }
          });
          console.log(`Created class: ${name} (Grade ${grade.level})`);
        }
      }
    }
  }

  // SUBJECT
  console.log("Ensuring Subjects...");
  const requiredSubjects = [
    "Urdu",
    "English",
    "Islamiat",
    "Pakistan Studies",
    "Physics",
    "Chemistry",
    "Biology",
    "Mathematics",
    "Computer Science"
  ];

  for (const subjectName of requiredSubjects) {
    await prisma.subject.upsert({
      where: { name: subjectName },
      update: {},
      create: { name: subjectName },
    });
    console.log(`✓ Created/verified subject: ${subjectName}`);
  }

  console.log("Seeding structure completed successfully.");
}

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