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

exports.addSalary = async (req, res) => {
  try {
    const { employee, grossSalary, totalDeduction, monthOfPayment } = req.body;

    if (!employee || grossSalary == null || totalDeduction == null || !monthOfPayment) {
      return res.status(400).json({ message: 'Employee, gross salary, deduction, and payment month are required' });
    }

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

    const netSalary = Number(grossSalary) - Number(totalDeduction);

    const salary = await Salary.create({
      employee,
      grossSalary,
      totalDeduction,
      netSalary,
      monthOfPayment,
    });

    res.status(201).json(salary);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.getSalaries = async (req, res) => {
  try {
    const salaries = await Salary.find().populate({
      path: 'employee',
      populate: { path: 'department' },
    });
    res.json(salaries);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.getSalaryById = async (req, res) => {
  try {
    const salary = await Salary.findById(req.params.id).populate({
      path: 'employee',
      populate: { path: 'department' },
    });

    if (!salary) {
      return res.status(404).json({ message: 'Salary record not found' });
    }

    res.json(salary);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.updateSalary = async (req, res) => {
  try {
    const { grossSalary, totalDeduction, monthOfPayment } = req.body;
    const salary = await Salary.findById(req.params.id);

    if (!salary) {
      return res.status(404).json({ message: 'Salary record not found' });
    }

    if (grossSalary != null) salary.grossSalary = grossSalary;
    if (totalDeduction != null) salary.totalDeduction = totalDeduction;
    if (monthOfPayment) salary.monthOfPayment = monthOfPayment;

    salary.netSalary = Number(salary.grossSalary) - Number(salary.totalDeduction);
    await salary.save();

    const updated = await Salary.findById(req.params.id).populate({
      path: 'employee',
      populate: { path: 'department' },
    });
    res.json(updated);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.deleteSalary = async (req, res) => {
  try {
    const salary = await Salary.findByIdAndDelete(req.params.id);
    if (!salary) {
      return res.status(404).json({ message: 'Salary record not found' });
    }
    res.json({ message: 'Salary record deleted successfully' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
