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

exports.getAll = async (req, res) => {
  try {
    const { status, department, search } = req.query;
    let filter = {};

    if (status) {
      filter.EmpStatus = status;
    }
    if (department) {
      filter.Department = department;
    }
    if (search) {
      filter.$or = [
        { EmpFirstName: { $regex: search, $options: 'i' } },
        { EmpLastName: { $regex: search, $options: 'i' } },
        { EmpEmail: { $regex: search, $options: 'i' } },
        { EmpTelephone: { $regex: search, $options: 'i' } }
      ];
    }

    const employees = await Employee.find(filter)
      .populate('Department', 'DepartName')
      .populate('Position', 'PosName')
      .sort({ EmpFirstName: 1 });
    res.json(employees);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.getById = async (req, res) => {
  try {
    const employee = await Employee.findById(req.params.id)
      .populate('Department', 'DepartName')
      .populate('Position', 'PosName');
    if (!employee) {
      return res.status(404).json({ message: 'Employee not found' });
    }
    res.json(employee);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.create = async (req, res) => {
  try {
    const employee = await Employee.create(req.body);
    const populated = await Employee.findById(employee._id)
      .populate('Department', 'DepartName')
      .populate('Position', 'PosName');
    res.status(201).json(populated);
  } catch (error) {
    if (error.code === 11000) {
      return res.status(400).json({ message: 'Email already exists' });
    }
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map(e => e.message);
      return res.status(400).json({ message: messages.join(', ') });
    }
    res.status(500).json({ message: error.message });
  }
};

exports.update = async (req, res) => {
  try {
    const employee = await Employee.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true }
    )
      .populate('Department', 'DepartName')
      .populate('Position', 'PosName');
    if (!employee) {
      return res.status(404).json({ message: 'Employee not found' });
    }
    res.json(employee);
  } catch (error) {
    if (error.code === 11000) {
      return res.status(400).json({ message: 'Email already exists' });
    }
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map(e => e.message);
      return res.status(400).json({ message: messages.join(', ') });
    }
    res.status(500).json({ message: error.message });
  }
};

exports.remove = async (req, res) => {
  try {
    const User = require('../models/User');
    const userExists = await User.findOne({ Employee: req.params.id });
    if (userExists) {
      return res.status(400).json({
        message: 'Cannot delete employee. A user account is linked to this employee.'
      });
    }
    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: error.message });
  }
};

exports.getStatusReport = async (req, res) => {
  try {
    const employees = await Employee.find({
      EmpStatus: { $in: ['On Leave', 'On Mission'] }
    })
      .populate('Department', 'DepartName')
      .populate('Position', 'PosName')
      .select('EmpFirstName EmpLastName EmpStatus Department')
      .sort({ EmpFirstName: 1 });
    res.json(employees);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.search = async (req, res) => {
  try {
    const { q } = req.query;
    if (!q) {
      return res.status(400).json({ message: 'Search query is required' });
    }
    const employees = await Employee.find({
      $or: [
        { EmpFirstName: { $regex: q, $options: 'i' } },
        { EmpLastName: { $regex: q, $options: 'i' } },
        { EmpEmail: { $regex: q, $options: 'i' } },
        { EmpTelephone: { $regex: q, $options: 'i' } }
      ]
    })
      .populate('Department', 'DepartName')
      .populate('Position', 'PosName')
      .sort({ EmpFirstName: 1 });
    res.json(employees);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};
