import { expect, test } from "@playwright/test";

import {
  PRIMARY_THREAD_ID,
  openChat,
  reuseThreadChatEntry,
  skipIfMissingThread,
  waitForMessageListReady,
} from "./support/chat-helpers";

test.use({
  video: "on",
});

test.describe("聊天工作台 / 错误提示", () => {
  test("DF-ERR-001 对话流失败时显示错误 toast", async ({ page }, testInfo) => {
    skipIfMissingThread(testInfo, PRIMARY_THREAD_ID, "FRONTEND_E2E_THREAD_ID");

    await openChat(page, reuseThreadChatEntry(PRIMARY_THREAD_ID!));
    await waitForMessageListReady(page, { requireMessages: false });

    await page.route("**/*", async (route) => {
      const request = route.request();
      if (request.method() === "POST" && /\/runs\b/.test(request.url())) {
        await route.abort("failed");
        return;
      }
      await route.continue();
    });

    const textarea = page.locator("textarea[name='message']");
    const submit = page.locator("button[aria-label='Submit']");
    await textarea.fill("触发错误 toast 测试");
    await submit.click({ force: true });

    await expect(
      page
        .locator("[data-sonner-toast]")
        .filter({ hasText: "出现了某些错误。" })
        .first(),
    ).toBeVisible({ timeout: 10_000 });
  });

  test("DF-ERR-002 相同错误短时间不重复弹 toast", async ({
    page,
  }, testInfo) => {
    skipIfMissingThread(testInfo, PRIMARY_THREAD_ID, "FRONTEND_E2E_THREAD_ID");

    await openChat(page, reuseThreadChatEntry(PRIMARY_THREAD_ID!));
    await waitForMessageListReady(page, { requireMessages: false });

    await page.route("**/*", async (route) => {
      const request = route.request();
      if (request.method() === "POST" && /\/runs\b/.test(request.url())) {
        await route.abort("failed");
        return;
      }
      await route.continue();
    });

    const textarea = page.locator("textarea[name='message']");
    const submit = page.locator("button[aria-label='Submit']");
    const errorToasts = page.locator('[data-sonner-toast][data-type="error"]');

    await textarea.fill("触发重复错误 toast 测试 1");
    await submit.click({ force: true });

    await expect(errorToasts.first()).toBeVisible({ timeout: 10_000 });
    await expect(errorToasts).toHaveCount(1);

    // 在去重窗口（2s）内再次触发同类错误，不应新增 toast
    await textarea.fill("触发重复错误 toast 测试 2");
    await submit.click({ force: true });

    await expect(errorToasts).toHaveCount(1);
  });
});
