-- =====================================================================================
-- RPC: rpc_admin_kefu_auto_reply_save
-- 位置：docs/sql/30_rpc/kefu/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端新增或更新自动回复配置
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_kefu_auto_reply_save(
    p_id UUID DEFAULT NULL,
    p_keyword TEXT DEFAULT NULL,
    p_content TEXT DEFAULT NULL,
    p_reply_type TEXT DEFAULT 'text',
    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 id = auth.uid() AND role IN ('admin', 'analytics')
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    -- 2. 新增
    IF p_id IS NULL THEN
        IF p_keyword IS NULL OR p_content IS NULL THEN
            RAISE EXCEPTION 'Missing required fields: keyword or content';
        END IF;

        INSERT INTO public.ml_kefu_auto_replies (
            keyword, content, reply_type, status
        ) VALUES (
            p_keyword, p_content, p_reply_type, p_status
        ) RETURNING id INTO v_id;
    ELSE
        -- 3. 更新
        UPDATE public.ml_kefu_auto_replies
        SET 
            keyword = COALESCE(p_keyword, keyword),
            content = COALESCE(p_content, content),
            reply_type = COALESCE(p_reply_type, reply_type),
            status = COALESCE(p_status, status),
            updated_at = now()
        WHERE id = p_id
        RETURNING id INTO v_id;

        IF v_id IS NULL THEN
            RAISE EXCEPTION 'Auto reply record not found';
        END IF;
    END IF;

    RETURN v_id;
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_kefu_auto_reply_save IS '管理员新增或更新自动回复配置';
