-- RPC: rpc_admin_delete_permission
-- 管理端删除功能权限/菜单（支持级联软删除关联的角色权限映射）

CREATE OR REPLACE FUNCTION public.rpc_admin_delete_permission(
    p_id UUID
)
RETURNS BOOLEAN
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
    v_ok BOOLEAN;
    v_user_id UUID;
BEGIN
    -- 1. 权限检查 (使用通用权限校验函数，权限编码: permission:delete)
    IF NOT public.check_admin_permission('permission:delete') THEN
        RAISE EXCEPTION 'Permission denied: permission:delete';
    END IF;

    -- 2. 获取当前操作用户 ID
    SELECT id INTO v_user_id
    FROM public.ak_users
    WHERE auth_id = auth.uid();

    -- 3. 级联软删除：先删除所有关联了该权限的角色映射
    UPDATE public.ak_role_permissions
    SET deleted_at = now(),
        deleted_by = v_user_id
    WHERE permission_id = p_id AND deleted_at IS NULL;

    -- 4. 最后软删除权限本身
    UPDATE public.ak_permissions 
    SET deleted_at = now(),
        deleted_by = v_user_id
    WHERE id = p_id AND deleted_at IS NULL;

    GET DIAGNOSTICS v_ok = ROW_COUNT;
    RETURN v_ok;
END;
$$;

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