-- =====================================================================================
-- 函数: check_admin_permission
-- 描述: 通用的 RBAC 权限校验函数
-- 参数: p_permission_code - 权限编码 (如 'role:delete', 'user:view')
-- 返回: BOOLEAN
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.check_admin_permission(
    p_permission_code TEXT DEFAULT NULL
)
RETURNS BOOLEAN
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
    v_user_id UUID;
    v_role TEXT;
BEGIN
    -- 1. 获取当前登录用户的 Profile ID 和角色
    SELECT id, role INTO v_user_id, v_role
    FROM public.ak_users
    WHERE auth_id = auth.uid();

    -- 2. 未登录或未找到 Profile
    IF v_user_id IS NULL THEN
        RETURN FALSE;
    END IF;

    -- 3. 超级管理员拥有所有权限 (保持向下兼容)
    IF v_role = 'admin' THEN
        RETURN TRUE;
    END IF;

    -- 4. 如果指定了权限编码，则检查 ak_permissions 体系
    IF p_permission_code IS NOT NULL THEN
        RETURN EXISTS (
            SELECT 1 
            FROM public.ak_admin_roles ar
            JOIN public.ak_role_permissions rp ON ar.role_id = rp.role_id
            JOIN public.ak_permissions p ON rp.permission_id = p.id
            WHERE ar.admin_id = v_user_id
              AND p.code = p_permission_code
              AND p.deleted_at IS NULL
              AND ar.deleted_at IS NULL
        );
    END IF;

    RETURN FALSE;
END;
$$;

-- 授权
REVOKE ALL ON FUNCTION public.check_admin_permission(TEXT) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.check_admin_permission(TEXT) TO authenticated;
