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

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

// ========== 意图检测测试 ==========
Deno.test("finance-genui: 收入查询应被识别", async () => {
  const response = await callGenUI({ message: '本月收入' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(data.success, true);
});

Deno.test("finance-genui: 交易记录查询应被识别", async () => {
  const response = await callGenUI({ message: '交易记录' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(data.success, true);
});

Deno.test("finance-genui: 充值方案查询应被识别", async () => {
  const response = await callGenUI({ message: '充值方案' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(data.success, true);
});

// ========== UI Schema 契约测试 ==========
Deno.test("finance-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));
  }
});

Deno.test("finance-genui: 应能返回stats_row展示关键指标", async () => {
  const response = await callGenUI({ message: '财务报表' });
  const data: GenUIResponse = await response.json();
  
  assertEquals(data.success, true);
});
