const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const userModel = require('../models/userModel');
const db = require('../db/config');

exports.register = async (req, res) => {
  const { name, email, password, role } = req.body;
  try {
    const hashedPassword = await bcrypt.hash(password, 10);
    await userModel.createUser({ name, email, password: hashedPassword, role });
    res.json({ message: 'User registered successfully' });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

exports.getUserById = async (req, res) => {
  try {
    const user = await userModel.getUserById(req.params.id);
    if (!user) return res.status(404).json({ error: 'User not found' });
    res.json(user);
  } catch (err) {
    console.error('Get User By ID Error:', err);
    res.status(500).json({ error: err.message });
  }
};

exports.login = async (req, res) => {
  const { email, password } = req.body;
  try {
    const user = await userModel.getUserByEmail(email);
    if (!user || !(await bcrypt.compare(password, user.password))) {
      return res.status(401).json({ message: 'Invalid credentials' });
    }

    const token = jwt.sign(
      {
        id: user.id,
        role: user.role,
        name: user.name,
        email: user.email,
        // pages: user.pages, // ✅ from joined query
      },
      'secret123',
      { expiresIn: '1d' }
    );

    res.json({ token });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

exports.getUsers = async (req, res) => {
  try {
    const users = await userModel.getAllUsers();
    res.json(users);
  } catch (err) {
    console.error('Get Users Error:', err);
    res.status(500).json({ error: err.message });
  }
};

exports.updateUser = async (req, res) => {
  const userId = req.params.id;
  const { name, email, role } = req.body;

  try {
    await userModel.updateUser({ id: userId, name, email, role });
    res.json({ message: 'User updated successfully' });
  } catch (err) {
    console.error('Update User Error:', err);
    res.status(500).json({ error: err.message });
  }
};

exports.changePassword = async (req, res) => {
  const userId = req.params.id;
  const { newPassword } = req.body;

  if (!newPassword) return res.status(400).json({ error: 'Password is required' });

  try {
    const hashed = await bcrypt.hash(newPassword, 10);
    await userModel.updatePassword(userId, hashed);
    res.json({ message: 'Password updated successfully' });
  } catch (err) {
    console.error('Change Password Error:', err);
    res.status(500).json({ error: err.message });
  }
};

exports.getMe = async (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ message: 'Unauthorized' });

  try {
    const decoded = jwt.verify(token, 'secret123');
    res.json(decoded);
  } catch (err) {
    res.status(401).json({ message: 'Invalid token' });
  }
};

exports.getUserMenus = async (req, res) => {
  const userId = req.params.id;

  const [[user]] = await db.query('SELECT role FROM users WHERE id = ?', [userId]);

  const [menus] = await db.query(`
    SELECT p.id, p.label, p.path, p.icon, p.parent_id, p.order, p.show_in_menu
    FROM pages p
    JOIN role_page_access rp ON rp.page_id = p.id
    WHERE rp.role_id = ? 
    ORDER BY p.parent_id, p.order
  `, [user.role]);

  res.json(menus);
};
