/**
 * 单元测试：ETLTasks 页面
 *
 * _Requirements: 3.1, 3.2, 3.3, 3.4, 10.4_
 *
 * - 测试默认 Tab 为 config（发起）
 * - 测试 5 个 Tab 内容正确渲染
 * - 测试 URL 参数驱动 Tab 选择
 */

import { describe, it, expect, vi, beforeAll, afterEach } from "vitest";
import { render, screen, cleanup } from "@testing-library/react";
import "@testing-library/jest-dom/vitest";
import { MemoryRouter } from "react-router-dom";

/* ------------------------------------------------------------------ */
/*  Ant Design jsdom 兼容：polyfill window.matchMedia                   */
/* ------------------------------------------------------------------ */

beforeAll(() => {
  Object.defineProperty(window, "matchMedia", {
    writable: true,
    value: vi.fn().mockImplementation((query: string) => ({
      matches: false,
      media: query,
      onchange: null,
      addListener: vi.fn(),
      removeListener: vi.fn(),
      addEventListener: vi.fn(),
      removeEventListener: vi.fn(),
      dispatchEvent: vi.fn(),
    })),
  });
});

/* ------------------------------------------------------------------ */
/*  Mock 子组件，避免内部 API 调用                                      */
/* ------------------------------------------------------------------ */

vi.mock("../pages/TaskConfig", () => ({
  default: () => <div data-testid="mock-task-config">TaskConfig Mock</div>,
}));
vi.mock("../pages/TaskManager", () => ({
  QueueTab: () => <div data-testid="mock-queue-tab">QueueTab Mock</div>,
  HistoryTab: () => <div data-testid="mock-history-tab">HistoryTab Mock</div>,
}));
vi.mock("../components/ScheduleTab", () => ({
  default: () => <div data-testid="mock-schedule-tab">ScheduleTab Mock</div>,
}));
vi.mock("../pages/ETLStatus", () => ({
  default: () => <div data-testid="mock-etl-status">ETLStatus Mock</div>,
}));

import ETLTasks from "../pages/ETLTasks";

afterEach(() => {
  cleanup();
});

/* ------------------------------------------------------------------ */
/*  测试：默认 Tab 为 config（Requirements 3.1, 3.2）                    */
/* ------------------------------------------------------------------ */

describe("ETLTasks — 默认 Tab (Requirements 3.1, 3.2)", () => {
  it("无 ?tab 参数时，默认激活 config Tab（发起）", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    const activeTab = document.querySelector(".ant-tabs-tab-active");
    expect(activeTab).not.toBeNull();
    expect(activeTab!.textContent).toContain("发起");
  });

  it("无效 ?tab 参数时，回退到默认 config Tab", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks?tab=invalid"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    const activeTab = document.querySelector(".ant-tabs-tab-active");
    expect(activeTab).not.toBeNull();
    expect(activeTab!.textContent).toContain("发起");
  });
});

/* ------------------------------------------------------------------ */
/*  测试：4 个 Tab 内容正确渲染（Requirements 3.2, 3.3, 3.4）            */
/* ------------------------------------------------------------------ */

describe("ETLTasks — 5 个 Tab 内容渲染 (Requirements 3.2, 3.3, 3.4)", () => {
  it("config Tab 渲染 TaskConfig 组件", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks?tab=config"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    expect(screen.getByTestId("mock-task-config")).toBeInTheDocument();
  });

  it("queue Tab 渲染 QueueTab 组件", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks?tab=queue"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    expect(screen.getByTestId("mock-queue-tab")).toBeInTheDocument();
  });

  it("schedule Tab 渲染 ScheduleTab 组件", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks?tab=schedule"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    expect(screen.getByTestId("mock-schedule-tab")).toBeInTheDocument();
  });

  it("history Tab 渲染 HistoryTab 组件", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks?tab=history"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    expect(screen.getByTestId("mock-history-tab")).toBeInTheDocument();
  });

  it("status Tab 渲染 ETLStatus 组件", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks?tab=status"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    expect(screen.getByTestId("mock-etl-status")).toBeInTheDocument();
  });

  it("页面标题包含「ETL 任务管理」", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    expect(screen.getByText("ETL 任务管理")).toBeInTheDocument();
  });

  it("5 个 Tab 标签文本正确：发起、队列、调度、历史、状态", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    const tabs = document.querySelectorAll(".ant-tabs-tab");
    expect(tabs).toHaveLength(5);

    const tabTexts = Array.from(tabs).map((t) => t.textContent);
    expect(tabTexts).toContain("发起");
    expect(tabTexts).toContain("队列");
    expect(tabTexts).toContain("调度");
    expect(tabTexts).toContain("历史");
    expect(tabTexts).toContain("状态");
  });
});

/* ------------------------------------------------------------------ */
/*  测试：URL 参数驱动 Tab 选择（Requirement 10.4）                      */
/* ------------------------------------------------------------------ */

describe("ETLTasks — URL 参数驱动 Tab 选择 (Requirement 10.4)", () => {
  it("?tab=config 激活「发起」Tab", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks?tab=config"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    const activeTab = document.querySelector(".ant-tabs-tab-active");
    expect(activeTab).not.toBeNull();
    expect(activeTab!.textContent).toContain("发起");
  });

  it("?tab=queue 激活「队列」Tab", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks?tab=queue"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    const activeTab = document.querySelector(".ant-tabs-tab-active");
    expect(activeTab).not.toBeNull();
    expect(activeTab!.textContent).toContain("队列");
  });

  it("?tab=schedule 激活「调度」Tab", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks?tab=schedule"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    const activeTab = document.querySelector(".ant-tabs-tab-active");
    expect(activeTab).not.toBeNull();
    expect(activeTab!.textContent).toContain("调度");
  });

  it("?tab=history 激活「历史」Tab", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks?tab=history"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    const activeTab = document.querySelector(".ant-tabs-tab-active");
    expect(activeTab).not.toBeNull();
    expect(activeTab!.textContent).toContain("历史");
  });

  it("?tab=status 激活「状态」Tab", () => {
    render(
      <MemoryRouter initialEntries={["/etl-tasks?tab=status"]}>
        <ETLTasks />
      </MemoryRouter>,
    );

    const activeTab = document.querySelector(".ant-tabs-tab-active");
    expect(activeTab).not.toBeNull();
    expect(activeTab!.textContent).toContain("状态");
  });
});
