const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const User = require("../models/userSchema") // Adjust the path as necessary

exports.register = async (req, res) => {
  const { name, email, password, role } = req.body;
  const hashed = await bcrypt.hash(password, 10);
  const user = await User.create({ name, email, password: hashed, role });
  res.json(user);
};

exports.login = async (req, res) => {
  try {
    const { email, password } = req.body;
    const user = await User.findOne({ email }).populate('tenantId', 'name').populate({
      path: 'role',  // Fixed: Added 'path' and corrected 'select' typo
      select: 'name permissions',
      populate: {
        path: 'permissions.resource',  // Nested populate for permissions.resource
        select: 'name displayName'
      }
    });
    if (!user) {
      return res.status(401).json({ message: 'Invalid email or password' });
    }
    const isMatch = await bcrypt.compare(password, user.passwordHash);
    if (!isMatch) {
      return res.status(401).json({ message: 'Invalid password' });
    }
    console.log(user);
    user.lastLogin = new Date();
    await user.save();
    user.passwordHash = undefined; 
    user.__v = undefined; 
    user._id = user._id.toString(); 
    user.tenantId = user.tenantId ? user.tenantId.toString() : null; // Convert tenantId to string if it exists
    user.role = user.role ? user.role.toString() : null; // Convert role to string if it exists
    // Generate JWT token
    const token = jwt.sign({ userId: user._id, role: user.role, tenantId:user?.tenantId }, process.env.JWT_SECRET, { expiresIn: '1h' });
    return res.status(200).json({
      user,
      token,
      message: 'Login successful'
    });
  } catch (error) {
    res.status(500).json({ message: 'Internal server error' });
  }
};
