import 'dotenv/config';
import mongoose from 'mongoose';
import { connectDB } from './config/db.js';
import User from './models/User.js';
import Department from './models/Department.js';
import Employee from './models/Employee.js';
import Payroll from './models/Payroll.js';
import Student from './models/Student.js';
import StudentPayment from './models/StudentPayment.js';
import { calcPayrollFromEmployee, monthLabel } from './utils/payrollCalc.js';

const departments = [
  { name: 'Mathematics', code: 'MATH', headName: 'Dr. Sarah Chen', budget: 120000 },
  { name: 'Science', code: 'SCI', headName: 'Prof. James Wilson', budget: 135000 },
  { name: 'English', code: 'ENG', headName: 'Ms. Emily Davis', budget: 110000 },
  { name: 'Administration', code: 'ADM', headName: 'Mr. Robert Lee', budget: 95000 },
  { name: 'Sports & PE', code: 'PE', headName: 'Coach Michael Brown', budget: 75000 },
];

const employeesData = [
  {
    employeeId: 'EMP001',
    firstName: 'Alice',
    lastName: 'Johnson',
    email: 'alice.johnson@school.edu',
    phone: '+1 555-0101',
    role: 'teacher',
    joinDate: new Date('2019-08-15'),
    salary: { basic: 4500, housing: 800, transport: 300, medical: 200, bonus: 500 },
    deductions: { tax: 650, pension: 350, insurance: 120, loan: 0 },
  },
  {
    employeeId: 'EMP002',
    firstName: 'David',
    lastName: 'Martinez',
    email: 'david.martinez@school.edu',
    phone: '+1 555-0102',
    role: 'teacher',
    joinDate: new Date('2020-01-10'),
    salary: { basic: 4200, housing: 750, transport: 300, medical: 200, bonus: 400 },
    deductions: { tax: 600, pension: 320, insurance: 120, loan: 150 },
  },
  {
    employeeId: 'EMP003',
    firstName: 'Priya',
    lastName: 'Sharma',
    email: 'priya.sharma@school.edu',
    phone: '+1 555-0103',
    role: 'principal',
    joinDate: new Date('2015-06-01'),
    salary: { basic: 7500, housing: 1200, transport: 500, medical: 350, bonus: 1000 },
    deductions: { tax: 1200, pension: 550, insurance: 180, loan: 0 },
  },
  {
    employeeId: 'EMP004',
    firstName: 'James',
    lastName: 'Okonkwo',
    email: 'james.okonkwo@school.edu',
    phone: '+1 555-0104',
    role: 'support',
    joinDate: new Date('2021-03-20'),
    salary: { basic: 2800, housing: 400, transport: 250, medical: 150, bonus: 200 },
    deductions: { tax: 380, pension: 200, insurance: 90, loan: 0 },
  },
  {
    employeeId: 'EMP005',
    firstName: 'Lisa',
    lastName: 'Anderson',
    email: 'lisa.anderson@school.edu',
    phone: '+1 555-0105',
    role: 'librarian',
    joinDate: new Date('2018-09-05'),
    salary: { basic: 3800, housing: 600, transport: 280, medical: 180, bonus: 350 },
    deductions: { tax: 520, pension: 280, insurance: 110, loan: 80 },
  },
  {
    employeeId: 'EMP006',
    firstName: 'Marcus',
    lastName: 'Taylor',
    email: 'marcus.taylor@school.edu',
    phone: '+1 555-0106',
    role: 'counselor',
    joinDate: new Date('2017-11-12'),
    salary: { basic: 4800, housing: 850, transport: 320, medical: 220, bonus: 450 },
    deductions: { tax: 700, pension: 380, insurance: 125, loan: 0 },
  },
];

const studentsData = [
  { studentId: 'STU001', firstName: 'Emma', lastName: 'Wilson', grade: 'Grade 10', section: 'A', tuitionFee: 4500, parentName: 'John Wilson', parentPhone: '+1 555-1001', email: 'emma.w@student.edu' },
  { studentId: 'STU002', firstName: 'Noah', lastName: 'Brown', grade: 'Grade 9', section: 'B', tuitionFee: 4200, parentName: 'Lisa Brown', parentPhone: '+1 555-1002', email: 'noah.b@student.edu' },
  { studentId: 'STU003', firstName: 'Olivia', lastName: 'Garcia', grade: 'Grade 11', section: 'A', tuitionFee: 4800, parentName: 'Carlos Garcia', parentPhone: '+1 555-1003', email: 'olivia.g@student.edu' },
  { studentId: 'STU004', firstName: 'Liam', lastName: 'Patel', grade: 'Grade 8', section: 'C', tuitionFee: 4000, parentName: 'Raj Patel', parentPhone: '+1 555-1004', email: 'liam.p@student.edu' },
  { studentId: 'STU005', firstName: 'Sophia', lastName: 'Kim', grade: 'Grade 12', section: 'A', tuitionFee: 5000, parentName: 'Min Kim', parentPhone: '+1 555-1005', email: 'sophia.k@student.edu' },
  { studentId: 'STU006', firstName: 'Ethan', lastName: 'Moore', grade: 'Grade 10', section: 'B', tuitionFee: 4500, parentName: 'Kate Moore', parentPhone: '+1 555-1006', email: 'ethan.m@student.edu' },
];

async function seed() {
  await connectDB();
  await Promise.all([
    User.deleteMany(),
    Department.deleteMany(),
    Employee.deleteMany(),
    Payroll.deleteMany(),
    Student.deleteMany(),
    StudentPayment.deleteMany(),
  ]);

  const admin = await User.create({
    name: 'Admin User',
    email: 'admin@school.edu',
    password: 'admin123',
    role: 'admin',
  });

  const depts = await Department.insertMany(departments);
  const deptIds = depts.map((d) => d._id);

  const employees = [];
  for (let i = 0; i < employeesData.length; i++) {
    const emp = await Employee.create({
      ...employeesData[i],
      department: deptIds[i % deptIds.length],
      status: 'active',
    });
    employees.push(emp);
  }

  const now = new Date();
  const month = now.getMonth() + 1;
  const year = now.getFullYear();

  for (const emp of employees) {
    const calc = calcPayrollFromEmployee(emp);
    await Payroll.create({
      employee: emp._id,
      month,
      year,
      periodLabel: monthLabel(month, year),
      ...calc,
      status: Math.random() > 0.4 ? 'paid' : 'processed',
      paidAt: Math.random() > 0.4 ? new Date() : undefined,
      processedBy: admin._id,
    });
  }

  const students = await Student.insertMany(
    studentsData.map((s) => ({
      ...s,
      enrollmentDate: new Date('2024-09-01'),
      status: 'active',
    }))
  );

  const paymentTypes = ['tuition', 'transport', 'library', 'exam'];
  const methods = ['cash', 'card', 'bank_transfer', 'online'];
  for (const student of students) {
    const partial = Math.floor(student.tuitionFee * (0.3 + Math.random() * 0.5));
    await StudentPayment.create({
      student: student._id,
      amount: partial,
      paymentType: 'tuition',
      paymentMethod: methods[Math.floor(Math.random() * methods.length)],
      status: 'completed',
      term: 'Term 1',
      academicYear: '2025-2026',
      paidAt: new Date(),
      recordedBy: admin._id,
    });
    if (Math.random() > 0.5) {
      await StudentPayment.create({
        student: student._id,
        amount: 200 + Math.floor(Math.random() * 300),
        paymentType: paymentTypes[Math.floor(Math.random() * paymentTypes.length)],
        paymentMethod: 'cash',
        status: 'completed',
        term: 'Term 1',
        academicYear: '2025-2026',
        paidAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000),
        recordedBy: admin._id,
      });
    }
  }

  await StudentPayment.create({
    student: students[0]._id,
    amount: 500,
    paymentType: 'tuition',
    paymentMethod: 'bank_transfer',
    status: 'pending',
    term: 'Term 2',
    academicYear: '2025-2026',
    recordedBy: admin._id,
  });

  console.log('Seed complete!');
  console.log('Login: admin@school.edu / admin123');
  process.exit(0);
}

seed().catch((e) => {
  console.error(e);
  process.exit(1);
});
