import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';

const prisma = new PrismaClient();

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

  // Clean existing data
  await prisma.settings.deleteMany();
  await prisma.echeanceMensuelle.deleteMany();
  await prisma.echeancier.deleteMany();
  await prisma.paiement.deleteMany();
  await prisma.document.deleteMany();
  await prisma.etudiant.deleteMany();
  await prisma.filiere.deleteMany();
  await prisma.anneeScolaire.deleteMany();
  await prisma.user.deleteMany();

  // Create users
  const adminPassword = await bcrypt.hash('admin123', 10);
  const directeurPassword = await bcrypt.hash('dir123', 10);

  await prisma.user.create({
    data: { email: 'admin@ispm.ma', password: adminPassword, role: 'ADMIN', name: 'Admin ISPM' },
  });
  await prisma.user.create({
    data: { email: 'directeur@ispm.ma', password: directeurPassword, role: 'DIRECTEUR', name: 'Yassine El Amrani' },
  });

  await prisma.settings.create({
    data: {
      id: 1,
      nomCommercial: 'ISPM',
      logoFilename: null,
    },
  });

  console.log('Users created');

  // Create academic years
  const prevYear = await prisma.anneeScolaire.create({
    data: {
      label: '2023-2024',
      startDate: new Date('2023-09-01'),
      endDate: new Date('2024-07-30'),
      isActive: false,
    },
  });

  const activeYear = await prisma.anneeScolaire.create({
    data: {
      label: '2024-2025',
      startDate: new Date('2024-09-01'),
      endDate: new Date('2025-07-30'),
      isActive: true,
    },
  });

  console.log('Academic years created');

  // Create filieres for active year
  const devDigital = await prisma.filiere.create({
    data: {
      name: 'Developpement Digital',
      niveau: 'Technicien Specialise',
      duree: '2 ans',
      fraisScolarite: 42000,
      maxPlaces: 50,
      anneeScolaireId: activeYear.id,
    },
  });

  const commerce = await prisma.filiere.create({
    data: {
      name: 'Commerce et Gestion',
      niveau: 'Technicien Specialise',
      duree: '2 ans',
      fraisScolarite: 38000,
      maxPlaces: 45,
      anneeScolaireId: activeYear.id,
    },
  });

  const infra = await prisma.filiere.create({
    data: {
      name: 'Infrastructure Digitale',
      niveau: 'Technicien Specialise',
      duree: '2 ans',
      fraisScolarite: 40000,
      maxPlaces: 40,
      anneeScolaireId: activeYear.id,
    },
  });

  const design = await prisma.filiere.create({
    data: {
      name: 'Design Multimedia',
      niveau: 'Technicien Specialise',
      duree: '2 ans',
      fraisScolarite: 36000,
      maxPlaces: 35,
      anneeScolaireId: activeYear.id,
    },
  });

  // Also create filieres for previous year
  await prisma.filiere.createMany({
    data: [
      { name: 'Developpement Digital', niveau: 'Technicien Specialise', duree: '2 ans', fraisScolarite: 40000, maxPlaces: 45, anneeScolaireId: prevYear.id },
      { name: 'Commerce et Gestion', niveau: 'Technicien Specialise', duree: '2 ans', fraisScolarite: 36000, maxPlaces: 40, anneeScolaireId: prevYear.id },
      { name: 'Infrastructure Digitale', niveau: 'Technicien Specialise', duree: '2 ans', fraisScolarite: 38000, maxPlaces: 35, anneeScolaireId: prevYear.id },
      { name: 'Design Multimedia', niveau: 'Technicien Specialise', duree: '2 ans', fraisScolarite: 34000, maxPlaces: 30, anneeScolaireId: prevYear.id },
    ],
  });

  console.log('Filieres created');

  // Create students
  const studentsData = [
    { nom: 'El Amrani', prenom: 'Youssef', cin: 'BK123456', dateNaissance: '2002-03-15', telephone: '06 12 34 56 78', email: 'y.elamrani@email.com', adresse: '12 Rue Ibn Sina, Gueliz, Marrakech', filiereId: devDigital.id, niveau: '2eme annee', statut: 'ACTIF' },
    { nom: 'Benali', prenom: 'Fatima Zahra', cin: 'BK234567', dateNaissance: '2003-07-22', telephone: '06 23 45 67 89', email: 'fz.benali@email.com', adresse: '45 Avenue Mohammed V, Marrakech', filiereId: commerce.id, niveau: '1ere annee', statut: 'ACTIF' },
    { nom: 'Tazi', prenom: 'Ahmed', cin: 'BK345678', dateNaissance: '2001-11-08', telephone: '06 34 56 78 90', email: 'a.tazi@email.com', adresse: '78 Rue de la Liberte, Marrakech', filiereId: infra.id, niveau: '2eme annee', statut: 'SUSPENDU' },
    { nom: 'Idrissi', prenom: 'Salma', cin: 'BK456789', dateNaissance: '2003-01-30', telephone: '06 45 67 89 01', email: 's.idrissi@email.com', adresse: '23 Boulevard Zerktouni, Marrakech', filiereId: design.id, niveau: '1ere annee', statut: 'ACTIF' },
    { nom: 'Chraibi', prenom: 'Omar', cin: 'BK567890', dateNaissance: '2002-05-14', telephone: '06 56 78 90 12', email: 'o.chraibi@email.com', adresse: '56 Rue Moulay Ali, Marrakech', filiereId: devDigital.id, niveau: '2eme annee', statut: 'ABANDON' },
    { nom: 'Benchekroun', prenom: 'Nadia', cin: 'BK678901', dateNaissance: '2001-09-25', telephone: '06 67 89 01 23', email: 'n.benchekroun@email.com', adresse: '89 Avenue Hassan II, Marrakech', filiereId: commerce.id, niveau: '2eme annee', statut: 'DIPLOME' },
    { nom: 'Alaoui', prenom: 'Karim', cin: 'BK789012', dateNaissance: '2003-04-18', telephone: '06 78 90 12 34', email: 'k.alaoui@email.com', adresse: '34 Rue Bab Agnaou, Marrakech', filiereId: infra.id, niveau: '1ere annee', statut: 'ACTIF' },
    { nom: 'Fassi', prenom: 'Houda', cin: 'BK890123', dateNaissance: '2002-12-03', telephone: '06 89 01 23 45', email: 'h.fassi@email.com', adresse: '67 Boulevard Allal El Fassi, Marrakech', filiereId: design.id, niveau: '1ere annee', statut: 'ACTIF' },
  ];

  const months = ['Septembre', 'Octobre', 'Novembre', 'Decembre', 'Janvier', 'Fevrier', 'Mars', 'Avril', 'Mai', 'Juin'];

  for (const studentData of studentsData) {
    const student = await prisma.etudiant.create({
      data: {
        nom: studentData.nom,
        prenom: studentData.prenom,
        cin: studentData.cin,
        dateNaissance: new Date(studentData.dateNaissance),
        telephone: studentData.telephone,
        email: studentData.email,
        adresse: studentData.adresse,
        filiereId: studentData.filiereId,
        niveau: studentData.niveau,
        dateInscription: new Date('2024-09-15'),
        anneeScolaireId: activeYear.id,
        statut: studentData.statut,
      },
    });

    // Get filiere tuition
    const filiere = await prisma.filiere.findUnique({ where: { id: studentData.filiereId } });
    if (!filiere) continue;

    const montantMensuel = Math.round(filiere.fraisScolarite / 10);

    // Create echeancier
    const echeancier = await prisma.echeancier.create({
      data: {
        etudiantId: student.id,
        anneeScolaireId: activeYear.id,
        montantTotal: filiere.fraisScolarite,
        nombreMensualites: 10,
      },
    });

    // Determine how many months are paid based on student
    let paidMonths = 0;
    if (studentData.cin === 'BK123456') paidMonths = 7; // Youssef - 7 months paid
    else if (studentData.cin === 'BK234567') paidMonths = 10; // Fatima - fully paid
    else if (studentData.cin === 'BK345678') paidMonths = 4; // Ahmed - 4 months (suspended)
    else if (studentData.cin === 'BK456789') paidMonths = 7; // Salma - 7 months
    else if (studentData.cin === 'BK567890') paidMonths = 3; // Omar - 3 months (abandon)
    else if (studentData.cin === 'BK678901') paidMonths = 10; // Nadia - fully paid
    else if (studentData.cin === 'BK789012') paidMonths = 6; // Karim - 6 months
    else if (studentData.cin === 'BK890123') paidMonths = 7; // Houda - 7 months

    // Create monthly echeances
    for (let i = 0; i < 10; i++) {
      const year = i < 4 ? 2024 : 2025;
      const isPaid = i < paidMonths;
      const isLate = !isPaid && i < 8; // Current month is ~May 2025 (index 8)

      const lastMontant = i === 9
        ? filiere.fraisScolarite - montantMensuel * 9
        : montantMensuel;

      await prisma.echeanceMensuelle.create({
        data: {
          echeancierId: echeancier.id,
          mois: `${months[i]} ${year}`,
          montantDu: lastMontant,
          montantPaye: isPaid ? lastMontant : 0,
          datePaiement: isPaid ? new Date(year, i < 4 ? i + 8 : i - 4, 15) : null,
          statut: isPaid ? 'PAYE' : isLate ? 'EN_RETARD' : 'A_VENIR',
        },
      });
    }

    // Create payment records for paid months
    if (paidMonths > 0) {
      const modes = ['ESPECES', 'VIREMENT', 'CHEQUE'];
      for (let i = 0; i < paidMonths; i++) {
        const year = i < 4 ? 2024 : 2025;
        const month = i < 4 ? i + 8 : i - 4; // Sept=8, Oct=9, Nov=10, Dec=11, Jan=0...

        const lastMontant = i === 9
          ? filiere.fraisScolarite - montantMensuel * 9
          : montantMensuel;

        await prisma.paiement.create({
          data: {
            etudiantId: student.id,
            montant: lastMontant,
            datePaiement: new Date(year, month, 15),
            modePaiement: modes[i % 3],
          },
        });
      }
    }

    // Create documents for some students
    if (studentData.cin === 'BK123456' || studentData.cin === 'BK234567') {
      await prisma.document.create({
        data: {
          etudiantId: student.id,
          type: 'CONTRAT',
          filename: 'sample-contrat.pdf',
          originalName: 'contrat-inscription.pdf',
          mimeType: 'application/pdf',
        },
      });
      await prisma.document.create({
        data: {
          etudiantId: student.id,
          type: 'CIN',
          filename: 'sample-cin.pdf',
          originalName: 'copie-cin.pdf',
          mimeType: 'application/pdf',
        },
      });
    }
    if (studentData.cin === 'BK234567') {
      await prisma.document.create({
        data: {
          etudiantId: student.id,
          type: 'DIPLOME',
          filename: 'sample-diplome.pdf',
          originalName: 'diplome-bac.pdf',
          mimeType: 'application/pdf',
        },
      });
    }
  }

  console.log('Students, echeanciers, payments, and documents created');

  // Add more students to reach ~143 total (as shown in frontend pagination)
  const additionalNames = [
    { nom: 'Bouazza', prenom: 'Mehdi' }, { nom: 'Lahlou', prenom: 'Sara' },
    { nom: 'Kettani', prenom: 'Amine' }, { nom: 'Berrada', prenom: 'Imane' },
    { nom: 'Filali', prenom: 'Rachid' }, { nom: 'Hajji', prenom: 'Zineb' },
    { nom: 'Ouazzani', prenom: 'Hamza' }, { nom: 'Sefrioui', prenom: 'Leila' },
    { nom: 'Bennani', prenom: 'Adil' }, { nom: 'Chaoui', prenom: 'Khadija' },
    { nom: 'Tahiri', prenom: 'Mouad' }, { nom: 'Amrani', prenom: 'Hajar' },
    { nom: 'Belhaj', prenom: 'Yassir' }, { nom: 'Kadiri', prenom: 'Asmae' },
    { nom: 'Ziani', prenom: 'Othmane' }, { nom: 'Rami', prenom: 'Soukaina' },
    { nom: 'Naciri', prenom: 'Bilal' }, { nom: 'Guessous', prenom: 'Meryem' },
    { nom: 'Sqalli', prenom: 'Reda' }, { nom: 'Benjelloun', prenom: 'Ghita' },
  ];

  const filieres = [devDigital, commerce, infra, design];
  const niveaux = ['1ere annee', '2eme annee'];

  for (let i = 0; i < additionalNames.length; i++) {
    const { nom, prenom } = additionalNames[i];
    const filiere = filieres[i % 4];
    const niveau = niveaux[i % 2];
    const cin = `BX${(100000 + i).toString()}`;

    const student = await prisma.etudiant.create({
      data: {
        nom,
        prenom,
        cin,
        dateNaissance: new Date(2002, i % 12, (i % 28) + 1),
        telephone: `06 ${(10 + i).toString().padStart(2, '0')} ${(20 + i).toString().padStart(2, '0')} ${(30 + i).toString().padStart(2, '0')} ${(40 + i).toString().padStart(2, '0')}`,
        email: `${prenom.toLowerCase().replace(' ', '')}.${nom.toLowerCase()}@email.com`,
        adresse: `${10 + i} Rue ${['Atlas', 'Majorelle', 'Koutoubia', 'Menara'][i % 4]}, Marrakech`,
        filiereId: filiere.id,
        niveau,
        dateInscription: new Date('2024-09-15'),
        anneeScolaireId: activeYear.id,
        statut: 'ACTIF',
      },
    });

    const montantMensuel = Math.round(filiere.fraisScolarite / 10);
    const paidMonths = 5 + (i % 4); // 5-8 months paid

    const echeancier = await prisma.echeancier.create({
      data: {
        etudiantId: student.id,
        anneeScolaireId: activeYear.id,
        montantTotal: filiere.fraisScolarite,
        nombreMensualites: 10,
      },
    });

    for (let m = 0; m < 10; m++) {
      const year = m < 4 ? 2024 : 2025;
      const isPaid = m < paidMonths;
      const isLate = !isPaid && m < 8;
      const lastMontant = m === 9 ? filiere.fraisScolarite - montantMensuel * 9 : montantMensuel;

      await prisma.echeanceMensuelle.create({
        data: {
          echeancierId: echeancier.id,
          mois: `${months[m]} ${year}`,
          montantDu: lastMontant,
          montantPaye: isPaid ? lastMontant : 0,
          datePaiement: isPaid ? new Date(year, m < 4 ? m + 8 : m - 4, 15) : null,
          statut: isPaid ? 'PAYE' : isLate ? 'EN_RETARD' : 'A_VENIR',
        },
      });
    }

    const modes = ['ESPECES', 'VIREMENT', 'CHEQUE'];
    for (let m = 0; m < paidMonths; m++) {
      const year = m < 4 ? 2024 : 2025;
      const month = m < 4 ? m + 8 : m - 4;
      const lastMontant = m === 9 ? filiere.fraisScolarite - montantMensuel * 9 : montantMensuel;

      await prisma.paiement.create({
        data: {
          etudiantId: student.id,
          montant: lastMontant,
          datePaiement: new Date(year, month, 10 + (i % 15)),
          modePaiement: modes[m % 3],
        },
      });
    }
  }

  console.log('Additional students created (total ~28)');
  console.log('Seed completed successfully!');
}

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