-- =====================================================================================
-- RPC: rpc_admin_user_label_set_status
-- 位置：docs/sql/30_rpc/user/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：设置用户标签状态（启用/禁用）
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_user_label_set_status(
    p_id UUID,
    p_status INT
)
RETURNS BOOLEAN
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_ok BOOLEAN;
BEGIN
    -- 1. 权限检查
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE auth_id = auth.uid() AND role IN ('admin', 'analytics')
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    UPDATE public.ak_user_labels
    SET status = p_status,
        updated_at = now()
    WHERE id = p_id AND deleted_at IS NULL;

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