import pool from '../config/db.js';

export function authorize(permission) {
  return async (req, res, next) => {
    if (!req.user || !req.user.role) {
      return res.status(401).json({ error: "Access Denied. User claims are missing role context." });
    }

    const userRole = req.user.role;

    try {
      // Look up if the role has the requested permission
      const query = `
        SELECT rp.role_id 
        FROM role_permissions rp
        JOIN permissions p ON rp.permission_id = p.id
        JOIN roles r ON rp.role_id = r.id
        WHERE r.name = ? AND p.name = ?
      `;

      const [rows] = await pool.query(query, [userRole, permission]);

      if (rows.length === 0) {
        return res.status(430).json({ error: `Forbidden. Role '${userRole}' lacks required permission '${permission}'.` });
      }

      next();
    } catch (err) {
      console.error("RBAC middleware query error:", err);
      return res.status(500).json({ error: "Internal server error performing RBAC security audit." });
    }
  };
}

export default authorize;
