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

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

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

    const user = await User.findOne({ UserName: UserName.toLowerCase() }).populate('Employee');

    if (!user) {
      return res.status(401).json({ message: 'Invalid credentials' });
    }

    const isMatch = await user.matchPassword(Password);
    if (!isMatch) {
      return res.status(401).json({ message: 'Invalid credentials' });
    }

    const role = user.role || 'user';
    req.session.userId = user._id;
    req.session.userName = user.UserName;
    req.session.role = role;

    res.json({
      message: 'Login successful',
      user: {
        _id: user._id,
        UserName: user.UserName,
        Employee: user.Employee,
        role: role
      }
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.register = async (req, res) => {
  try {
    const { UserName, Password, EmpFirstName, EmpLastName, EmpGender, EmpDateOfBirth, EmpEmail, EmpTelephone, EmpAddress } = req.body;

    if (!UserName || !Password || !EmpFirstName || !EmpLastName || !EmpEmail) {
      return res.status(400).json({ message: 'Username, password, first name, last name, and email are required' });
    }

    const existingUser = await User.findOne({ UserName: UserName.toLowerCase() });
    if (existingUser) {
      return res.status(400).json({ message: 'Username already taken' });
    }

    const existingEmail = await Employee.findOne({ EmpEmail });
    if (existingEmail) {
      return res.status(400).json({ message: 'Email already registered to an employee' });
    }

    const employee = await Employee.create({
      EmpFirstName,
      EmpLastName,
      EmpGender: EmpGender || 'Male',
      EmpDateOfBirth: EmpDateOfBirth || new Date('2000-01-01'),
      EmpEmail,
      EmpTelephone: EmpTelephone || '',
      EmpAddress: EmpAddress || '',
      EmpHireDate: new Date(),
      EmpStatus: 'Active',
      Department: req.body.Department || null,
      Position: req.body.Position || null
    });

    // Determine role: first user should be admin
    const usersCount = await User.countDocuments();
    const role = usersCount === 0 ? 'admin' : 'user';
    const user = await User.create({ UserName, Password, Employee: employee._id, role });
    const populated = await User.findById(user._id).populate('Employee');

    req.session.userId = user._id;
    req.session.userName = user.UserName;
    req.session.role = user.role;
    res.status(201).json({
      message: 'Registration successful',
      user: {
        _id: user._id,
        UserName: user.UserName,
        Employee: populated.Employee,
        role: role
      }
    });
  } catch (error) {
    if (error.code === 11000) {
      return res.status(400).json({ message: 'Username or 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.logout = (req, res) => {
  req.session.destroy((err) => {
    if (err) {
      return res.status(500).json({ message: 'Could not logout' });
    }
    res.clearCookie('connect.sid');
    res.json({ message: 'Logout successful' });
  });
};

exports.checkSession = (req, res) => {
  if (req.session && req.session.userId) {
    res.json({ authenticated: true, userName: req.session.userName, role: req.session.role });
  } else {
    res.json({ authenticated: false });
  }
};
