-- =====================================================================================
-- RPC: rpc_admin_user_label_save
-- 位置：docs/sql/30_rpc/user/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：新增/更新用户标签（逻辑删除记录默认不允许更新）
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_user_label_save(
    p_id UUID DEFAULT NULL,
    p_name TEXT,
    p_color TEXT DEFAULT NULL,
    p_remark TEXT DEFAULT NULL,
    p_status INT DEFAULT 1
)
RETURNS UUID
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_id UUID;
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;

    -- 2. 参数校验
    IF p_name IS NULL OR length(trim(p_name)) = 0 THEN
        RAISE EXCEPTION 'Invalid name';
    END IF;

    -- 3. 新增
    IF p_id IS NULL THEN
        INSERT INTO public.ak_user_labels(
            name, color, remark, status,
            created_at, updated_at, deleted_at
        ) VALUES (
            p_name, p_color, p_remark, COALESCE(p_status, 1),
            now(), now(), NULL
        )
        RETURNING id INTO v_id;

        RETURN v_id;
    END IF;

    -- 4. 更新（不允许更新已删除记录）
    UPDATE public.ak_user_labels
    SET
        name = p_name,
        color = p_color,
        remark = p_remark,
        status = COALESCE(p_status, status),
        updated_at = now()
    WHERE id = p_id AND deleted_at IS NULL
    RETURNING id INTO v_id;

    IF v_id IS NULL THEN
        RAISE EXCEPTION 'Not found or deleted';
    END IF;

    RETURN v_id;
END;
$$;
