import { describe, expect, it, vi } from "vitest";

import {
  buildSearchStageTimingSnapshot,
  formatDurationMs,
  normalizeSearchStageTiming,
} from "./search-stage-timing.ts";

describe("search-stage-timing", () => {
  it("calculates elapsed time for an active stage without ending it", () => {
    vi.setSystemTime(new Date("2026-04-28T08:00:12.500Z"));

    expect(
      normalizeSearchStageTiming({
        task_id: "task-1",
        material_id: "material-1",
        stage_order: 2,
        stage_label: "LLM 匹配",
        stage_kind: "keyword",
        started_at: "2026-04-28T08:00:10.000Z",
        status: "running",
      }),
    ).toMatchObject({
      taskId: "task-1",
      materialId: "material-1",
      stageOrder: 2,
      stageLabel: "LLM 匹配",
      stageKind: "keyword",
      startedAt: "2026-04-28T08:00:10.000Z",
      endedAt: null,
      durationMs: null,
      elapsedMs: 2500,
      status: "running",
    });
  });

  it("keeps completed duration fixed and formats it for display", () => {
    const timing = normalizeSearchStageTiming({
      task_id: "task-1",
      material_id: "material-1",
      stage_order: 1,
      stage_label: "首轮搜索",
      stage_kind: "keyword",
      started_at: "2026-04-28T08:00:00.000Z",
      ended_at: "2026-04-28T08:01:05.400Z",
      duration_ms: 65400,
      status: "completed",
    });

    expect(timing.elapsedMs).toBe(65400);
    expect(timing.durationMs).toBe(65400);
    expect(formatDurationMs(timing.durationMs)).toBe("1分05秒");
  });

  it("returns null for legacy rows with no timing fields", () => {
    expect(
      normalizeSearchStageTiming({
        task_id: "task-legacy",
        material_id: "material-legacy",
        stage_order: 1,
        stage_label: "历史阶段",
        stage_kind: "keyword",
      }),
    ).toBeNull();
  });

  it("builds task-level snapshots with current, completed and total elapsed timing", () => {
    vi.setSystemTime(new Date("2026-04-28T08:02:00.000Z"));

    const snapshot = buildSearchStageTimingSnapshot({
      startedAt: "2026-04-28T08:00:00.000Z",
      finishedAt: null,
      searchProgress: {
        materialId: "material-2",
        materialName: "测试物料",
        stageOrder: 2,
        stageLabel: "图片搜索",
        stageKind: "image",
        stageStartedAt: "2026-04-28T08:01:30.000Z",
        status: "running",
      },
      completedStages: [
        {
          taskId: "task-1",
          materialId: "material-1",
          stageOrder: 1,
          stageLabel: "首轮搜索",
          stageKind: "keyword",
          startedAt: "2026-04-28T08:00:10.000Z",
          endedAt: "2026-04-28T08:01:00.000Z",
          durationMs: 50000,
          elapsedMs: 50000,
          status: "completed",
        },
      ],
    });

    expect(snapshot.currentStage?.elapsedMs).toBe(30000);
    expect(snapshot.completedStages).toHaveLength(1);
    expect(snapshot.totalElapsedMs).toBe(120000);
  });
});
