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

import type { Provider } from "../../../src/shared/api";

import { ProviderTable } from "../../../src/web/pages/models/components/ProviderTable";
import { renderWithProviders } from "../test-utils";

const OPENAI_PROVIDER: Provider = {
  apiKey: "sk-test",
  baseUrl: "https://api.openai.com/v1",
  createdAt: "2024-01-01T00:00:00.000Z",
  id: "pv1",
  name: "OpenAI",
  type: "openai",
  updatedAt: "2024-01-01T00:00:00.000Z",
};

const DEEPSEEK_PROVIDER: Provider = {
  apiKey: "sk-off",
  baseUrl: "https://api.deepseek.com/v1",
  createdAt: "2024-01-01T00:00:00.000Z",
  id: "pv2",
  name: "DeepSeek",
  type: "openai-compatible",
  updatedAt: "2024-01-01T00:00:00.000Z",
};

function clickLatestConfirmButton() {
  const buttons = screen.getAllByRole("button", { name: /OK|确定/ });
  fireEvent.click(buttons[buttons.length - 1]!);
}

describe("ProviderTable", () => {
  test("渲染供应商表格数据", () => {
    renderWithProviders(
      createElement(ProviderTable, {
        data: { items: [OPENAI_PROVIDER, DEEPSEEK_PROVIDER], page: 1, pageSize: 20, total: 2 },
        loading: false,
        onDelete: () => Promise.resolve(),
        onEdit: () => undefined,
        onPageChange: () => undefined,
        page: 1,
        pageSize: 20,
      }),
    );

    expect(screen.getAllByText("OpenAI").length).toBeGreaterThan(0);
    expect(screen.getByText("DeepSeek")).not.toBeNull();
    expect(screen.getByText("https://api.openai.com/v1")).not.toBeNull();
    expect(screen.queryByText("状态")).toBeNull();
    expect(screen.queryByRole("button", { name: "测试连接" })).toBeNull();
    expect(screen.queryByRole("button", { name: /启用|禁用/ })).toBeNull();
  });

  test("供应商表格操作触发 edit/delete", async () => {
    const onDelete = mock(() => Promise.resolve());
    const onEdit = mock(() => undefined);

    renderWithProviders(
      createElement(ProviderTable, {
        data: { items: [OPENAI_PROVIDER, DEEPSEEK_PROVIDER], page: 1, pageSize: 20, total: 2 },
        loading: false,
        onDelete,
        onEdit,
        onPageChange: () => undefined,
        page: 1,
        pageSize: 20,
      }),
    );

    fireEvent.click(screen.getAllByRole("button", { name: /编辑/ })[0]!);
    expect(onEdit).toHaveBeenCalledWith(OPENAI_PROVIDER);

    fireEvent.click(screen.getAllByRole("button", { name: /删除/ })[0]!);
    await waitFor(() => expect(screen.getByText("确认删除此供应商？")).not.toBeNull());
    clickLatestConfirmButton();
    await waitFor(() => expect(onDelete).toHaveBeenCalledWith("pv1"));
  });
});
