-- =====================================================================================
-- RPC: rpc_admin_article_delete
-- 位置：docs/sql/30_rpc/cms/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端删除文章记录（使用通用权限校验）
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_article_delete(
    p_id UUID
)
RETURNS BOOLEAN
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_ok BOOLEAN;
    v_user_id UUID;
BEGIN
    -- 1. 权限检查
    IF NOT public.check_admin_permission('cms:article:delete') THEN
        RAISE EXCEPTION 'Permission denied: cms:article:delete';
    END IF;

    -- 2. 获取当前操作用户 ID
    SELECT id INTO v_user_id FROM public.ak_users WHERE auth_id = auth.uid();

    -- 3. 执行软删除
    UPDATE public.ml_articles
    SET deleted_at = now(),
        deleted_by = v_user_id
    WHERE id = p_id AND deleted_at IS NULL;

    GET DIAGNOSTICS v_ok = ROW_COUNT;
    RETURN v_ok;
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_article_delete IS '管理员删除文章记录';
