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

CREATE OR REPLACE FUNCTION public.rpc_admin_user_level_save(
    p_id UUID DEFAULT NULL,
    p_name TEXT,
    p_level_weight INT,
    p_min_experience INT,
    p_discount_percent INT,
    p_is_visible BOOLEAN,
    p_status INT,
    p_icon_url TEXT DEFAULT NULL,
    p_bg_image_url TEXT DEFAULT NULL,
    p_bg_style_json JSONB DEFAULT NULL,
    p_remark TEXT DEFAULT NULL
)
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;

    IF p_level_weight < 0 OR p_min_experience < 0 THEN
        RAISE EXCEPTION 'Invalid level_weight or min_experience';
    END IF;

    IF p_discount_percent < 1 OR p_discount_percent > 100 THEN
        RAISE EXCEPTION 'Invalid discount_percent';
    END IF;

    -- 3. 新增
    IF p_id IS NULL THEN
        INSERT INTO public.ak_user_levels(
            name, level_weight, min_experience, discount_percent,
            is_visible, status,
            icon_url, bg_image_url, bg_style_json,
            remark,
            created_at, updated_at, deleted_at
        ) VALUES (
            p_name, p_level_weight, p_min_experience, p_discount_percent,
            p_is_visible, p_status,
            p_icon_url, p_bg_image_url, p_bg_style_json,
            p_remark,
            now(), now(), NULL
        )
        RETURNING id INTO v_id;

        RETURN v_id;
    END IF;

    -- 4. 更新（不允许更新已删除记录）
    UPDATE public.ak_user_levels
    SET
        name = p_name,
        level_weight = p_level_weight,
        min_experience = p_min_experience,
        discount_percent = p_discount_percent,
        is_visible = p_is_visible,
        status = p_status,
        icon_url = p_icon_url,
        bg_image_url = p_bg_image_url,
        bg_style_json = p_bg_style_json,
        remark = p_remark,
        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;
$$;
