-- 创建 Agent 测试结果表，用于 Coze 获取反馈
CREATE TABLE public.agent_test_results (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  trace_id TEXT NOT NULL,
  agent_type TEXT NOT NULL DEFAULT 'consumer',
  user_message TEXT NOT NULL,
  passed BOOLEAN NOT NULL DEFAULT false,
  issues TEXT[] DEFAULT '{}',
  response_summary JSONB DEFAULT '{}',
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);

-- 创建索引加速查询
CREATE INDEX idx_agent_test_results_agent_type ON public.agent_test_results(agent_type);
CREATE INDEX idx_agent_test_results_created_at ON public.agent_test_results(created_at DESC);

-- 自动清理旧记录（保留最近 100 条）
CREATE OR REPLACE FUNCTION public.cleanup_old_test_results()
RETURNS TRIGGER AS $$
BEGIN
  DELETE FROM public.agent_test_results 
  WHERE id NOT IN (
    SELECT id FROM public.agent_test_results 
    ORDER BY created_at DESC 
    LIMIT 100
  );
  RETURN NEW;
END;
$$ LANGUAGE plpgsql SET search_path = public;

CREATE TRIGGER cleanup_test_results_trigger
AFTER INSERT ON public.agent_test_results
FOR EACH STATEMENT
EXECUTE FUNCTION public.cleanup_old_test_results();

-- 添加注释
COMMENT ON TABLE public.agent_test_results IS 'Agent 测试结果记录，供 Coze 查询自身表现';
COMMENT ON COLUMN public.agent_test_results.trace_id IS '请求追踪ID';
COMMENT ON COLUMN public.agent_test_results.passed IS '测试是否通过';
COMMENT ON COLUMN public.agent_test_results.issues IS '发现的问题列表';