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

exports.getAll = async (req, res) => {
  try {
    const users = await User.find()
      .populate('Employee', 'EmpFirstName EmpLastName EmpEmail')
      .sort({ UserName: 1 });
    res.json(users);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.getById = async (req, res) => {
  try {
    const user = await User.findById(req.params.id)
      .populate('Employee', 'EmpFirstName EmpLastName EmpEmail');
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    res.json(user);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.create = async (req, res) => {
  try {
    const { UserName, Password, Employee } = req.body;

    if (!UserName || !Password || !Employee) {
      return res.status(400).json({ message: 'Username, password, and employee are required' });
    }

    const existingEmployee = await User.findOne({ Employee });
    if (existingEmployee) {
      return res.status(400).json({ message: 'This employee already has a user account' });
    }

    const user = await User.create({ UserName, Password, Employee });
    const populated = await User.findById(user._id)
      .populate('Employee', 'EmpFirstName EmpLastName EmpEmail');
    res.status(201).json(populated);
  } catch (error) {
    if (error.code === 11000) {
      return res.status(400).json({ message: 'Username 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 updateData = {};
    if (req.body.UserName) updateData.UserName = req.body.UserName;
    if (req.body.Password) updateData.Password = req.body.Password;
    if (req.body.Employee) updateData.Employee = req.body.Employee;

    if (req.body.Password) {
      const userDoc = await User.findById(req.params.id);
      if (!userDoc) {
        return res.status(404).json({ message: 'User not found' });
      }
      const salt = await require('bcryptjs').genSalt(10);
      updateData.Password = await require('bcryptjs').hash(req.body.Password, salt);
    }

    const user = await User.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true, runValidators: true }
    ).populate('Employee', 'EmpFirstName EmpLastName EmpEmail');

    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    res.json(user);
  } catch (error) {
    if (error.code === 11000) {
      return res.status(400).json({ message: 'Username already exists' });
    }
    res.status(500).json({ message: error.message });
  }
};

exports.remove = async (req, res) => {
  try {
    if (req.session.userId === req.params.id) {
      return res.status(400).json({ message: 'Cannot delete your own account' });
    }
    const user = await User.findByIdAndDelete(req.params.id);
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    res.json({ message: 'User deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};
