import { describe, expect, test } from "bun:test";
import { screen, waitFor } from "@testing-library/react";
import { createElement } from "react";

import { ModelSettingsCard } from "../../../../../src/web/features/settings/components/ModelSettingsCard";
import { installFetchMock, jsonResponse, renderWithProviders } from "../../../test-utils";

function mockSettingsResponse(defaultModels?: Record<string, string | null>): Response {
  return jsonResponse({ compact: false, defaultModels, theme: "system" });
}

function mockModelsResponse(items: Array<{ id: string; name: string }>): Response {
  return jsonResponse({
    items: items.map((m) => ({ ...m, capabilities: [], createdAt: "", externalId: "", providerId: "", updatedAt: "" })),
    page: 1,
    pageSize: 200,
    total: items.length,
  });
}

function mockEmptyModelsResponse(): Response {
  return mockModelsResponse([]);
}

describe("ModelSettingsCard", () => {
  test("渲染 7 个模型能力配置项", async () => {
    installFetchMock((call) => {
      if (call.url.includes("/api/settings")) return mockSettingsResponse();
      if (call.url.includes("/api/models")) return mockEmptyModelsResponse();
      return jsonResponse({});
    });

    renderWithProviders(createElement(ModelSettingsCard));

    await waitFor(() => {
      expect(screen.getByText("文本")).not.toBeNull();
      expect(screen.getByText("图片识别")).not.toBeNull();
      expect(screen.getByText("音频识别")).not.toBeNull();
      expect(screen.getByText("视频识别")).not.toBeNull();
      expect(screen.getByText("图片生成")).not.toBeNull();
      expect(screen.getByText("音频生成")).not.toBeNull();
      expect(screen.getByText("视频生成")).not.toBeNull();
    });
  }, 30000);

  test("回显已保存的默认模型值", async () => {
    installFetchMock((call) => {
      if (call.url.includes("/api/settings")) {
        return mockSettingsResponse({ imageRecognition: "model-b", text: "model-a" });
      }
      if (call.url.includes("/api/models")) {
        return mockModelsResponse([
          { id: "model-a", name: "GPT-4" },
          { id: "model-b", name: "Claude Vision" },
        ]);
      }
      return jsonResponse({});
    });

    renderWithProviders(createElement(ModelSettingsCard));

    await waitFor(() => {
      expect(screen.getByText("GPT-4")).not.toBeNull();
      expect(screen.getByText("Claude Vision")).not.toBeNull();
    });
  }, 30000);
});
