
-- name: GetUserPermissions :many
SELECT DISTINCT p.id,p.name,p.scope,p.description
FROM permissions p

-- From roles assigned directly to the user
LEFT JOIN role_permissions rp_user
    ON p.id = rp_user.permission_id
LEFT JOIN user_roles ur
    ON rp_user.role_id = ur.role_id AND ur.user_id = $1

-- From roles assigned to user's groups
LEFT JOIN user_groups ug
    ON ug.user_id = $1
LEFT JOIN group_roles gr
    ON ug.group_id = gr.group_id
LEFT JOIN role_permissions rp_group
    ON gr.role_id = rp_group.role_id AND rp_group.permission_id = p.id

-- Direct permissions to user
LEFT JOIN user_permissions up
    ON up.user_id = $1 AND up.permission_id = p.id

-- Direct permissions to user's groups
LEFT JOIN group_permissions gp
    ON gp.group_id = ug.group_id AND gp.permission_id = p.id

WHERE ur.user_id IS NOT NULL
   OR gr.group_id IS NOT NULL
   OR up.user_id IS NOT NULL
   OR gp.group_id IS NOT NULL
ORDER BY p.scope;
