-- RPC: rpc_admin_delete_role
-- 管理端删除角色（支持级联软删除关联权限）

CREATE OR REPLACE FUNCTION public.rpc_admin_delete_role(
    p_id UUID
)
RETURNS BOOLEAN
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
    v_ok BOOLEAN;
    v_user_id UUID;
BEGIN
    -- 1. 权限检查 (使用通用权限校验函数，权限编码: role:delete)
    IF NOT public.check_admin_permission('role:delete') THEN
        RAISE EXCEPTION 'Permission denied: role: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 role_id = p_id AND deleted_at IS NULL;

    -- 4. 级联软删除：再删除该角色下的所有管理员关联
    UPDATE public.ak_admin_roles
    SET deleted_at = now(),
        deleted_by = v_user_id
    WHERE role_id = p_id AND deleted_at IS NULL;

    -- 5. 最后软删除角色本身
    UPDATE public.ak_roles
    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_role(UUID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_delete_role(UUID) TO authenticated;
