/**
 * Marketing 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/marketing-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("marketing-genui: CORS预检请求应返回200", async () => {
  const response = await fetch(FUNCTION_URL, { method: 'OPTIONS' });
  await response.text();
  assertEquals(response.status, 200);
});

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

// ========== 意图检测测试 ==========
Deno.test("marketing-genui: 优惠券查询应返回coupon相关内容", async () => {
  const response = await callGenUI({ message: '查看优惠券' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(data.success, true);
  assertExists(data.ui_schema);
});

Deno.test("marketing-genui: 活动查询应返回campaign相关内容", async () => {
  const response = await callGenUI({ message: '营销活动列表' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(data.success, true);
  assertExists(data.ui_schema);
});

Deno.test("marketing-genui: 秒杀查询应被识别", async () => {
  const response = await callGenUI({ message: '秒杀活动' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(data.success, true);
});

Deno.test("marketing-genui: 拼团查询应被识别", async () => {
  const response = await callGenUI({ message: '拼团活动' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(data.success, true);
});

// ========== UI Schema 契约测试 ==========
Deno.test("marketing-genui: ui_schema结构应符合规范", async () => {
  const response = await callGenUI({ message: '营销数据' });
  const data: GenUIResponse = await response.json();
  
  if (data.ui_schema) {
    assert(['vertical', 'horizontal', 'grid'].includes(data.ui_schema.layout));
    assert(['sm', 'md', 'lg'].includes(data.ui_schema.gap));
    assert(Array.isArray(data.ui_schema.components));
  }
});

// ========== 营销特定组件测试 ==========
Deno.test("marketing-genui: 应能返回data_table用于展示活动列表", async () => {
  const response = await callGenUI({ message: '所有活动' });
  const data: GenUIResponse = await response.json();
  
  if (data.ui_schema) {
    const hasTable = data.ui_schema.components.some(c => 
      c.type === 'data_table' || 
      (c.type === 'container' && 
        (c.props as { children?: UIComponent[] }).children?.some(child => child.type === 'data_table'))
    );
    // 表格是可选的，根据数据情况
    assert(data.success);
  }
});

Deno.test("marketing-genui: 应能返回chart用于展示趋势", async () => {
  const response = await callGenUI({ message: '营销效果分析' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(data.success, true);
});
