-- A.3 Query: “User → Effective Permissions” (global + project)
-- เปลี่ยน :userId, :projectId ตามต้องการ (projectId ใส่ NULL ได้)
SET @uid := :userId;
SET @pid := :projectId;

SELECT DISTINCT p.perm_code
FROM (
  -- global roles
  SELECT rp.perm_id
  FROM user_roles ur
  JOIN role_permissions rp ON rp.role_id = ur.role_id
  WHERE ur.user_id = @uid

  UNION ALL
  -- project roles (ถ้ามี project)
  SELECT rp.perm_id
  FROM user_project_roles upr
  JOIN role_permissions rp ON rp.role_id = upr.role_id
  WHERE upr.user_id = @uid AND (@pid IS NOT NULL AND upr.project_id = @pid)
) x
JOIN permissions p ON p.perm_id = x.perm_id
ORDER BY p.perm_code;
-- End of A.3



