const Payroll = require("../models/Payroll");
const Employee = require("../models/Employee");

const createPayroll = async (req, res) => {
  try {
    const { employee, month, year, basicPay, allowances, deductions, netPay, paymentDate } = req.body;

    if (!employee || !month || !year || basicPay === undefined || netPay === undefined) {
      return res.status(400).json({ message: "Employee, month, year, basic pay and net pay are required" });
    }

    const employeeExists = await Employee.findById(employee);
    if (!employeeExists) {
      return res.status(404).json({ message: "Employee not found" });
    }

    const existingPayroll = await Payroll.findOne({ employee, month, year });
    if (existingPayroll) {
      return res.status(400).json({ message: "Payroll already exists for this employee for the given period" });
    }

    const payroll = await Payroll.create({
      employee,
      month,
      year,
      basicPay,
      allowances: allowances || 0,
      deductions: deductions || 0,
      netPay,
      paymentDate: paymentDate || Date.now()
    });

    const populatedPayroll = await Payroll.findById(payroll._id).populate("employee");

    res.status(201).json({ message: "Payroll processed successfully", payroll: populatedPayroll });
  } catch (error) {
    res.status(500).json({ message: "Payroll could not be created", error: error.message });
  }
};

const getPayrolls = async (req, res) => {
  try {
    const filter = {};

    if (req.query.month) filter.month = parseInt(req.query.month);
    if (req.query.year) filter.year = parseInt(req.query.year);
    if (req.query.employee) filter.employee = req.query.employee;

    const payrolls = await Payroll.find(filter)
      .populate("employee")
      .sort({ year: -1, month: -1 });

    res.json(payrolls);
  } catch (error) {
    res.status(500).json({ message: "Payrolls could not be retrieved", error: error.message });
  }
};

const getPayroll = async (req, res) => {
  try {
    const payroll = await Payroll.findById(req.params.id).populate("employee");

    if (!payroll) {
      return res.status(404).json({ message: "Payroll record not found" });
    }

    res.json(payroll);
  } catch (error) {
    res.status(500).json({ message: "Payroll could not be retrieved", error: error.message });
  }
};

const updatePayroll = async (req, res) => {
  try {
    const { basicPay, allowances, deductions, netPay, paymentDate } = req.body;

    const payroll = await Payroll.findByIdAndUpdate(
      req.params.id,
      { basicPay, allowances, deductions, netPay, paymentDate },
      { new: true, runValidators: true }
    ).populate("employee");

    if (!payroll) {
      return res.status(404).json({ message: "Payroll record not found" });
    }

    res.json({ message: "Payroll updated successfully", payroll });
  } catch (error) {
    res.status(500).json({ message: "Payroll could not be updated", error: error.message });
  }
};

const deletePayroll = async (req, res) => {
  try {
    const payroll = await Payroll.findByIdAndDelete(req.params.id);

    if (!payroll) {
      return res.status(404).json({ message: "Payroll record not found" });
    }

    res.json({ message: "Payroll record deleted successfully" });
  } catch (error) {
    res.status(500).json({ message: "Payroll could not be deleted", error: error.message });
  }
};

module.exports = {
  createPayroll,
  getPayrolls,
  getPayroll,
  updatePayroll,
  deletePayroll
};
