const mongoose = require('mongoose');
const Employee = require('../models/Employee');
const Department = require('../models/Department');
const Salary = require('../models/Salary');

function rangeForDaily() {
  const now = new Date();
  const start = new Date(now);
  start.setHours(0, 0, 0, 0);
  const end = new Date(now);
  end.setHours(23, 59, 59, 999);
  return { start, end };
}

function rangeForWeekly() {
  const now = new Date();
  const end = now;
  const start = new Date(now);
  start.setDate(start.getDate() - 6);
  start.setHours(0, 0, 0, 0);
  return { start, end };
}

function rangeForMonthly() {
  const now = new Date();
  const start = new Date(now.getFullYear(), now.getMonth(), 1);
  const end = new Date(now.getFullYear(), now.getMonth() + 1, 0);
  end.setHours(23, 59, 59, 999);
  return { start, end };
}

async function buildReport({ start, end }) {
  const salaries = await Salary.find({ createdAt: { $gte: start, $lte: end } })
    .populate({
      path: 'employee',
      populate: { path: 'department', model: 'Department' }
    })
    .sort({ createdAt: -1 });

  const employeeIds = [...new Set(salaries.map((s) => s.employee?._id).filter(Boolean))];
  const departmentIds = [...new Set(salaries.map((s) => s.employee?.department?._id).filter(Boolean))];

  const employees = employeeIds.length ? await Employee.find({ _id: { $in: employeeIds } }) : [];
  const departments = departmentIds.length ? await Department.find({ _id: { $in: departmentIds } }) : [];

  return { employees, departments, salaries };
}

async function dailyReport(req, res, next) {
  try {
    const range = rangeForDaily();
    const report = await buildReport(range);
    return res.status(200).json(report);
  } catch (err) {
    return next(err);
  }
}

async function weeklyReport(req, res, next) {
  try {
    const range = rangeForWeekly();
    const report = await buildReport(range);
    return res.status(200).json(report);
  } catch (err) {
    return next(err);
  }
}

async function monthlyReport(req, res, next) {
  try {
    const range = rangeForMonthly();
    const report = await buildReport(range);
    return res.status(200).json(report);
  } catch (err) {
    return next(err);
  }
}

module.exports = {
  dailyReport,
  weeklyReport,
  monthlyReport
};

