-- =====================================================================================
-- RPC: rpc_admin_article_category_save
-- 位置：docs/sql/30_rpc/cms/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端新增或更新文章分类
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_article_category_save(
    p_id UUID DEFAULT NULL,
    p_name TEXT DEFAULT NULL,
    p_icon TEXT DEFAULT NULL,
    p_sort INTEGER DEFAULT 0,
    p_status SMALLINT 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.ml_article_categories (
            name, icon, sort, status
        ) VALUES (
            p_name, p_icon, p_sort, p_status
        ) RETURNING id INTO v_id;
    ELSE
        -- 4. 更新
        UPDATE public.ml_article_categories
        SET 
            name = p_name,
            icon = COALESCE(p_icon, icon),
            sort = p_sort,
            status = p_status,
            updated_at = now()
        WHERE id = p_id
        RETURNING id INTO v_id;

        IF v_id IS NULL THEN
            RAISE EXCEPTION 'Category not found';
        END IF;
    END IF;

    RETURN v_id;
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_article_category_save IS '管理员新增或更新文章分类';
