-- =====================================================================================
-- RPC: rpc_admin_user_group_delete
-- 位置：docs/sql/30_rpc/user/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：逻辑删除用户分组（使用通用权限校验）
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_user_group_delete(
    p_id UUID
)
RETURNS BOOLEAN
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_ok BOOLEAN;
    v_user_id UUID;
BEGIN
    -- 1. 权限检查
    IF NOT public.check_admin_permission('user:group:delete') THEN
        RAISE EXCEPTION 'Permission denied: user:group:delete';
    END IF;

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

    -- 3. 逻辑删除
    UPDATE public.ak_user_groups
    SET deleted_at = now(), 
        updated_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;
$$;
