const db = require('../db/config');
const bcrypt = require('bcryptjs');

exports.createUser = async ({ name, email, password, role }) => {
  await db.query('INSERT INTO users (name, email, password, role) VALUES (?, ?, ?, ?)', [name, email, password, role]);
};

exports.getUserByEmail = async (email) => {
  const [[user]] = await db.query('SELECT * FROM users WHERE email = ?', [email]);
  if (!user) return null;

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

  // Build nested tree structure
  const map = {};
  const root = [];

  rows.forEach((page) => {
    map[page.id] = { ...page, children: [] };
  });

  rows.forEach((page) => {
    if (page.parent_id) {
      map[page.parent_id]?.children.push(map[page.id]);
    } else {
      root.push(map[page.id]);
    }
  });

  return {
    ...user,
    pages: root, // ✅ structured tree
  };
};
exports.getAllUsers = async () => {
  const [rows] = await db.query(`
    SELECT 
      u.id, 
      u.name, 
      u.email, 
      r.name AS role_name
    FROM users u
    LEFT JOIN roles r ON u.role = r.id
    ORDER BY u.id DESC
  `);
  return rows;
};

exports.getUserById = async (id) => {
  const [rows] = await db.query(
    `SELECT u.id, u.name, u.email, u.role, r.name AS role_name
     FROM users u
     LEFT JOIN roles r ON u.role = r.id
     WHERE u.id = ?
     LIMIT 1`,
    [id]
  );
  return rows[0] || null;
};

exports.updateUser = async ({ id, name, email, role }) => {
  await db.query(
    'UPDATE users SET name = ?, email = ?, role = ? WHERE id = ?',
    [name, email, role, id]
  );
};

exports.updatePassword = async (userId, hashedPassword) => {
  await db.query('UPDATE users SET password = ? WHERE id = ?', [hashedPassword, userId]);
};