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

exports.addEmployee = async (req, res) => {
  try {
    const {
      employeeNumber,
      firstName,
      lastName,
      address,
      position,
      telephone,
      gender,
      hiredDate,
      department,
    } = req.body;

    if (
      !employeeNumber ||
      !firstName ||
      !lastName ||
      !address ||
      !position ||
      !telephone ||
      !gender ||
      !hiredDate ||
      !department
    ) {
      return res.status(400).json({ message: 'All employee fields are required' });
    }

    const existing = await Employee.findOne({ employeeNumber: employeeNumber.trim() });
    if (existing) {
      return res.status(409).json({ message: 'Employee number already exists' });
    }

    const departmentExists = await Department.findById(department);
    if (!departmentExists) {
      return res.status(404).json({ message: 'Department not found' });
    }

    const employee = await Employee.create({
      employeeNumber,
      firstName,
      lastName,
      address,
      position,
      telephone,
      gender,
      hiredDate,
      department,
    });

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

exports.getEmployees = async (req, res) => {
  try {
    const employees = await Employee.find().populate('department');
    res.json(employees);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
