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

const createEmployee = async (req, res) => {
  try {
    const { employeeCode, firstName, lastName, department, position, baseSalary, hireDate, email, phone } = req.body;

    if (!employeeCode || !firstName || !lastName || !department || !position || !baseSalary || !hireDate) {
      return res.status(400).json({ message: "All required fields must be filled" });
    }

    const existingEmployee = await Employee.findOne({ employeeCode });
    if (existingEmployee) {
      return res.status(400).json({ message: "Employee code already exists" });
    }

    const employee = await Employee.create({
      employeeCode,
      firstName: firstName.trim(),
      lastName: lastName.trim(),
      department: department.trim(),
      position: position.trim(),
      baseSalary,
      hireDate,
      email,
      phone
    });

    res.status(201).json({ message: "Employee added successfully", employee });
  } catch (error) {
    res.status(500).json({ message: "Employee could not be created", error: error.message });
  }
};

const getEmployees = async (req, res) => {
  try {
    const employees = await Employee.find().sort({ lastName: 1 });
    res.json(employees);
  } catch (error) {
    res.status(500).json({ message: "Employees could not be retrieved", error: error.message });
  }
};

const getEmployee = async (req, res) => {
  try {
    const employee = await Employee.findById(req.params.id);

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

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

const updateEmployee = async (req, res) => {
  try {
    const { firstName, lastName, department, position, baseSalary, hireDate, email, phone } = req.body;

    const employee = await Employee.findByIdAndUpdate(
      req.params.id,
      { firstName, lastName, department, position, baseSalary, hireDate, email, phone },
      { new: true, runValidators: true }
    );

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

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

const deleteEmployee = async (req, res) => {
  try {
    const employee = await Employee.findByIdAndDelete(req.params.id);

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

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

module.exports = {
  createEmployee,
  getEmployees,
  getEmployee,
  updateEmployee,
  deleteEmployee
};
