// RunSelect: option labels (utc stamp · trigger · region count, partial
// suffix), one option per run, the other side's value disabled, and change
// propagation. Fabricated RunSummaryFile fixtures.

import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { RunSelect, runOptionLabel } from "@/components/compare/RunSelect";
import type { RunSummaryFile } from "@/lib/api-types";
import { mkOverviewRow } from "../helpers/mk-overview-row";

function mkRun(runId: string, over: Partial<RunSummaryFile> = {}): RunSummaryFile {
  return {
    runId,
    trigger: "schedule",
    status: "success",
    startedAt: "2026-09-01T02:00:00Z",
    finishedAt: "2026-09-01T02:10:00Z",
    regions: [mkOverviewRow("r1"), mkOverviewRow("r2")],
    ...over,
  };
}

describe("runOptionLabel", () => {
  it("labels a run with stamp, trigger, and region count", () => {
    expect(runOptionLabel(mkRun("run-20260901T020100"))).toBe("2026-09-01 10:00 UTC+8 · schedule · 2 regions");
  });

  it("appends the partial marker only for partial runs", () => {
    expect(runOptionLabel(mkRun("run-20260901T020100", { status: "partial" }))).toContain("· partial");
    expect(runOptionLabel(mkRun("run-20260901T020100"))).not.toContain("partial");
  });
});

describe("RunSelect", () => {
  const runs = [
    mkRun("run-20260901T020000"),
    mkRun("run-20260825T020000", { trigger: "manual", status: "partial" }),
    mkRun("run-20260818T020000"),
  ];

  it("renders one option per run and disables the other side's value", () => {
    render(
      <RunSelect sideLabel="Snapshot A" runs={runs} value="run-20260901T020000" otherValue="run-20260818T020000" onChange={() => {}} />,
    );
    const select = screen.getByLabelText("Snapshot A") as HTMLSelectElement;
    const options = [...select.querySelectorAll("option")];
    expect(options.length).toBe(3);
    expect(options.map((o) => o.value)).toEqual(runs.map((r) => r.runId));
    expect(options.find((o) => o.value === "run-20260818T020000")?.disabled).toBe(true);
    expect(options.find((o) => o.value === "run-20260825T020000")?.disabled).toBe(false);
  });

  it("reports the chosen runId on change", () => {
    const onChange = vi.fn();
    render(
      <RunSelect sideLabel="Snapshot A" runs={runs} value="run-20260901T020000" otherValue="run-20260818T020000" onChange={onChange} />,
    );
    fireEvent.change(screen.getByLabelText("Snapshot A"), { target: { value: "run-20260825T020000" } });
    expect(onChange).toHaveBeenCalledWith("run-20260825T020000");
  });
});
