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

CREATE OR REPLACE FUNCTION public.rpc_admin_article_save(
    p_id UUID DEFAULT NULL,
    p_category_id UUID DEFAULT NULL,
    p_title TEXT DEFAULT NULL,
    p_author TEXT DEFAULT NULL,
    p_image TEXT DEFAULT NULL,
    p_description TEXT DEFAULT NULL,
    p_content TEXT DEFAULT NULL,
    p_status SMALLINT DEFAULT 0,
    p_is_banner BOOLEAN DEFAULT FALSE,
    p_is_hot BOOLEAN DEFAULT FALSE,
    p_linked_product_id UUID 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_title IS NULL OR length(trim(p_title)) = 0 THEN
        RAISE EXCEPTION 'Invalid title';
    END IF;
    IF p_category_id IS NULL THEN
        RAISE EXCEPTION 'Category is required';
    END IF;

    -- 3. 新增
    IF p_id IS NULL THEN
        INSERT INTO public.ml_articles (
            category_id, title, author, image, description, content, 
            status, is_banner, is_hot, linked_product_id
        ) VALUES (
            p_category_id, p_title, p_author, p_image, p_description, p_content,
            p_status, p_is_banner, p_is_hot, p_linked_product_id
        ) RETURNING id INTO v_id;
    ELSE
        -- 4. 更新
        UPDATE public.ml_articles
        SET 
            category_id = COALESCE(p_category_id, category_id),
            title = COALESCE(p_title, title),
            author = COALESCE(p_author, author),
            image = COALESCE(p_image, image),
            description = COALESCE(p_description, description),
            content = COALESCE(p_content, content),
            status = COALESCE(p_status, status),
            is_banner = COALESCE(p_is_banner, is_banner),
            is_hot = COALESCE(p_is_hot, is_hot),
            linked_product_id = p_linked_product_id,
            updated_at = now()
        WHERE id = p_id
        RETURNING id INTO v_id;

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

    RETURN v_id;
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_article_save IS '管理员新增或更新文章内容';
