import { describe, expect, it } from "vitest";
import { buildChainPlanRequest, futureZrvOptions, type ZrvOption } from "./createChainWindows";
import type { ZrvWindowResponse } from "../../api/tguPlanApi";

const NOW = new Date(2026, 5, 3, 12, 0, 0).getTime();

function zrv(startIso: string, endIso: string, kppId = "KPP-1"): ZrvWindowResponse {
  return { startTime: startIso, endTime: endIso, kppId };
}

describe("futureZrvOptions", () => {
  it("keeps only future zones and sorts by start", () => {
    const windows = [
      zrv("2026-06-03T15:00:00", "2026-06-03T15:10:00"),
      zrv("2026-06-03T11:00:00", "2026-06-03T11:10:00"), // в прошлом → отбросить
      zrv("2026-06-03T13:00:00", "2026-06-03T13:10:00")
    ];
    const options = futureZrvOptions(windows, NOW);
    expect(options.map((o) => o.startMs)).toEqual([
      new Date(2026, 5, 3, 13, 0, 0).getTime(),
      new Date(2026, 5, 3, 15, 0, 0).getTime()
    ]);
  });

  it("produces UTC start/stop strings", () => {
    const [option] = futureZrvOptions([zrv("2026-06-03T13:00:00", "2026-06-03T13:10:00")], NOW);
    expect(option.start).toBe(new Date(2026, 5, 3, 13, 0, 0).toISOString());
    expect(option.stop).toBe(new Date(2026, 5, 3, 13, 10, 0).toISOString());
    expect(option.kppId).toBe("KPP-1");
  });
});

describe("buildChainPlanRequest", () => {
  const start: ZrvOption = {
    id: "a", startMs: Date.UTC(2026, 5, 3, 13, 0, 0), endMs: Date.UTC(2026, 5, 3, 13, 10, 0),
    start: "2026-06-03T13:00:00.000Z", stop: "2026-06-03T13:10:00.000Z", kppId: "KPP-1"
  };
  const end: ZrvOption = {
    id: "b", startMs: Date.UTC(2026, 5, 3, 15, 0, 0), endMs: Date.UTC(2026, 5, 3, 15, 10, 0),
    start: "2026-06-03T15:00:00.000Z", stop: "2026-06-03T15:10:00.000Z", kppId: "KPP-2"
  };

  it("spans from start zone begin to end zone finish and keeps the start kpp", () => {
    const req = buildChainPlanRequest("25544", "base-1", start, end);
    expect(req).toEqual({
      spacecraftId: "25544",
      basePlanId: "base-1",
      windowStart: "2026-06-03T13:00:00.000Z",
      windowStop: "2026-06-03T15:10:00.000Z",
      windowKppId: "KPP-1"
    });
  });

  it("allows a single-zone window (start == end zone)", () => {
    const req = buildChainPlanRequest("25544", null, start, start);
    expect(req.windowStart).toBe("2026-06-03T13:00:00.000Z");
    expect(req.windowStop).toBe("2026-06-03T13:10:00.000Z");
    expect(req.basePlanId).toBeNull();
  });

  it("throws when the end zone finishes before the start begins", () => {
    expect(() => buildChainPlanRequest("25544", null, end, start)).toThrow();
  });
});
