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

import { ToolPart } from "../../../../src/web/features/chat/parts/ToolPart";
import { renderWithProviders } from "../../test-utils";

describe("ToolPart 工具显示名", () => {
  test("无 toolMetadata 时使用 toolName", () => {
    const part = {
      input: { timezone: "Asia/Shanghai" },
      output: { iso: "2024-01-01T00:00:00.000Z", local: "2024年1月1日", timestamp: 1704067200000 },
      toolCallId: "call-1",
      toolName: "getCurrentTime",
      type: "tool-getCurrentTime",
    };

    renderWithProviders(createElement(ToolPart, { part }));

    expect(screen.getByText(/getCurrentTime/)).toBeTruthy();
  });

  test("有 toolMetadata.displayName 时优先使用显示名", () => {
    const part = {
      input: { timezone: "Asia/Shanghai" },
      output: { iso: "2024-01-01T00:00:00.000Z", local: "2024年1月1日", timestamp: 1704067200000 },
      toolCallId: "call-1",
      toolMetadata: { displayName: "获取当前时间" },
      toolName: "getCurrentTime",
      type: "tool-getCurrentTime",
    };

    renderWithProviders(createElement(ToolPart, { part }));

    expect(screen.getByText("获取当前时间")).toBeTruthy();
    expect(screen.queryByText(/getCurrentTime/)).toBeNull();
  });

  test("toolMetadata.displayName 非字符串时回退到 toolName", () => {
    const part = {
      input: {},
      output: {},
      toolCallId: "call-2",
      toolMetadata: { displayName: 123 },
      type: "tool-someTool",
    };

    renderWithProviders(createElement(ToolPart, { part }));

    expect(screen.getByText("someTool")).toBeTruthy();
  });

  test("错误状态时使用显示名", () => {
    const part = {
      errorText: "超时",
      toolCallId: "call-3",
      toolMetadata: { displayName: "获取当前时间" },
      type: "tool-getCurrentTime",
    };

    renderWithProviders(createElement(ToolPart, { part }));

    expect(screen.getByText(/获取当前时间.*失败/)).toBeTruthy();
  });
});
