import express from 'express';
import Employee from '../models/Employee.js';
import Department from '../models/Department.js';
import Payroll from '../models/Payroll.js';
import Student from '../models/Student.js';
import StudentPayment from '../models/StudentPayment.js';
import { protect } from '../middleware/auth.js';
import { monthLabel } from '../utils/payrollCalc.js';

const router = express.Router();
router.use(protect);

router.get('/stats', async (req, res, next) => {
  try {
    const now = new Date();
    const month = now.getMonth() + 1;
    const year = now.getFullYear();

    const monthStart = new Date(year, month - 1, 1);
    const monthEnd = new Date(year, month, 0, 23, 59, 59);

    const [
      totalEmployees,
      activeEmployees,
      departments,
      currentPayrolls,
      recentPayrolls,
      roleBreakdown,
      activeStudents,
      monthlyStudentPayments,
      recentStudentPayments,
      pendingStudentPayments,
    ] = await Promise.all([
      Employee.countDocuments(),
      Employee.countDocuments({ status: 'active' }),
      Department.countDocuments(),
      Payroll.find({ month, year }),
      Payroll.find()
        .sort({ createdAt: -1 })
        .limit(5)
        .populate('employee', 'firstName lastName employeeId'),
      Employee.aggregate([
        { $match: { status: 'active' } },
        { $group: { _id: '$role', count: { $sum: 1 } } },
      ]),
      Student.countDocuments({ status: 'active' }),
      StudentPayment.find({ paidAt: { $gte: monthStart, $lte: monthEnd }, status: 'completed' }),
      StudentPayment.find({ status: 'completed' })
        .sort({ paidAt: -1 })
        .limit(5)
        .populate('student', 'firstName lastName studentId grade'),
      StudentPayment.countDocuments({ status: 'pending' }),
    ]);

    const monthlyPayroll = currentPayrolls.reduce((s, p) => s + p.netPay, 0);
    const paidThisMonth = currentPayrolls.filter((p) => p.status === 'paid').length;
    const studentFeesCollected = monthlyStudentPayments.reduce((s, p) => s + p.amount, 0);

    const last6Months = [];
    for (let i = 5; i >= 0; i--) {
      let m = month - i;
      let y = year;
      while (m <= 0) {
        m += 12;
        y -= 1;
      }
      const records = await Payroll.find({ month: m, year: y });
      last6Months.push({
        label: monthLabel(m, y).split(' ')[0].slice(0, 3),
        gross: records.reduce((s, p) => s + p.grossPay, 0),
        net: records.reduce((s, p) => s + p.netPay, 0),
      });
    }

    res.json({
      totalEmployees,
      activeEmployees,
      departments,
      monthlyPayroll,
      paidThisMonth,
      pendingThisMonth: currentPayrolls.length - paidThisMonth,
      payrollCountThisMonth: currentPayrolls.length,
      roleBreakdown: roleBreakdown.map((r) => ({ role: r._id, count: r.count })),
      recentPayrolls,
      chartData: last6Months,
      currentPeriod: monthLabel(month, year),
      activeStudents,
      studentFeesCollected,
      studentPaymentCount: monthlyStudentPayments.length,
      pendingStudentPayments,
      recentStudentPayments,
    });
  } catch (err) {
    next(err);
  }
});

export default router;
