-- =====================================================================================
-- RPC: rpc_admin_article_get_detail
-- 位置：docs/sql/30_rpc/cms/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端获取指定文章的完整详情
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_article_get_detail(
    p_id UUID
)
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_item JSONB;
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. 获取详情
    SELECT jsonb_build_object(
        'id', a.id,
        'category_id', a.category_id,
        'category_name', c.name,
        'title', a.title,
        'author', a.author,
        'image', a.image,
        'description', a.description,
        'content', a.content,
        'status', a.status,
        'views', a.views,
        'is_banner', a.is_banner,
        'is_hot', a.is_hot,
        'linked_product_id', a.linked_product_id,
        'created_at', a.created_at,
        'updated_at', a.updated_at
    ) INTO v_item
    FROM public.ml_articles a
    LEFT JOIN public.ml_article_categories c ON c.id = a.category_id
    WHERE a.id = p_id;

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

    RETURN v_item;
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_article_get_detail IS '管理员获取文章完整详情';
