const Employee = require('../models/Employee');

const ON_LEAVE_STATUS = 'on leave';

exports.getOnLeaveByDepartment = async (req, res) => {
  try {
    const onLeaveEmployees = await Employee.find({ status: ON_LEAVE_STATUS })
      .populate('department position')
      .sort({ lastName: 1, firstName: 1 });

    const byDepartment = {};

    onLeaveEmployees.forEach((employee) => {
      const deptName = employee.department?.departmentName || 'Unassigned';
      if (!byDepartment[deptName]) {
        byDepartment[deptName] = [];
      }
      byDepartment[deptName].push({
        id: employee._id,
        firstName: employee.firstName,
        lastName: employee.lastName,
        email: employee.email,
        telephone: employee.telephone,
        position: employee.position?.posName || 'N/A',
        status: employee.status,
      });
    });

    const departments = Object.keys(byDepartment)
      .sort()
      .map((departmentName) => ({
        departmentName,
        employees: byDepartment[departmentName],
        count: byDepartment[departmentName].length,
      }));

    res.json({
      reportTitle: 'Employee Status Report — On Leave',
      totalOnLeave: onLeaveEmployees.length,
      departments,
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
