/**
 * Service GenUI Edge Function 测试
 * 使用 Deno 测试框架验证客服Agent GenUI接口功能
 */
import "https://deno.land/std@0.224.0/dotenv/load.ts";
import { assertEquals, assertExists, assert } from "https://deno.land/std@0.224.0/assert/mod.ts";

const SUPABASE_URL = Deno.env.get("VITE_SUPABASE_URL")!;
const SUPABASE_ANON_KEY = Deno.env.get("VITE_SUPABASE_PUBLISHABLE_KEY")!;

const FUNCTION_URL = `${SUPABASE_URL}/functions/v1/service-genui`;

// ========== 类型定义 ==========
interface UIComponent {
  type: string;
  id?: string;
  props: Record<string, unknown>;
}

interface UISchema {
  layout: 'vertical' | 'horizontal' | 'grid';
  gap: 'sm' | 'md' | 'lg';
  components: UIComponent[];
}

interface GenUIResponse {
  success: boolean;
  answer?: string;
  ui_schema?: UISchema;
  insights?: unknown[];
  intent?: string;
}

// ========== 辅助函数 ==========
async function callGenUI(body: Record<string, unknown>): Promise<Response> {
  return await fetch(FUNCTION_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'apikey': SUPABASE_ANON_KEY,
    },
    body: JSON.stringify(body),
  });
}

// ========== 基础功能测试 ==========
Deno.test("service-genui: CORS预检请求应返回200", async () => {
  const response = await fetch(FUNCTION_URL, { method: 'OPTIONS' });
  await response.text();
  assertEquals(response.status, 200);
});

Deno.test("service-genui: 基本消息应返回成功响应", async () => {
  const response = await callGenUI({ message: '售后概览' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(response.status, 200);
  assertEquals(data.success, true);
});

// ========== 意图检测测试 ==========
Deno.test("service-genui: 售后请求查询应被识别", async () => {
  const response = await callGenUI({ message: '待处理售后' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(data.success, true);
});

Deno.test("service-genui: 订单查询应被识别", async () => {
  const response = await callGenUI({ message: '订单状态' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(data.success, true);
});

Deno.test("service-genui: 退款查询应被识别", async () => {
  const response = await callGenUI({ message: '退款申请' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(data.success, true);
});

// ========== UI Schema 契约测试 ==========
Deno.test("service-genui: 售后统计应返回合理结构", async () => {
  const response = await callGenUI({ message: '售后统计' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(data.success, true);
  if (data.ui_schema) {
    assert(['vertical', 'horizontal', 'grid'].includes(data.ui_schema.layout));
    assert(Array.isArray(data.ui_schema.components));
  }
});
