import { describe, expect, it } from "vitest";
import { getFlightSearchDate } from "./flightSearchDate.js";
import type { IDirectFlight, IMultiLegFlight, IFlightLeg } from "./types.js";

function leg(local: string): IFlightLeg {
  return {
    arrival: {
      scheduled: { airport: "", airportCode: "", city: "", cityCode: "", countryCode: "" },
      times: {
        scheduledArrival: {
          dayChange: { value: 0, title: "" },
          local,
          localTime: "",
          tzOffset: 0,
          utc: "",
        },
      },
    },
    dayChange: 0,
    departure: {
      scheduled: { airport: "", airportCode: "", city: "", cityCode: "", countryCode: "" },
      checkingStatus: "Scheduled",
      times: {
        scheduledDeparture: {
          dayChange: { value: 0, title: "" },
          local,
          localTime: "",
          tzOffset: 0,
          utc: "",
        },
      },
    },
    equipment: {},
    flags: { checkinAvailable: false, returnToAirport: false, routeChanged: false },
    flyingTime: "",
    index: 0,
    operatingBy: {},
    status: "Scheduled",
    updated: "",
  };
}

describe("getFlightSearchDate", () => {
  it("uses scheduled local departure date instead of backend flightId.date", () => {
    const flight: IDirectFlight = {
      id: "SU6951",
      routeType: "Direct",
      flyingTime: "",
      operatingBy: {},
      status: "Arrived",
      flightId: {
        carrier: "SU",
        flightNumber: "6951",
        suffix: "",
        date: "2026-05-04",
        dateLT: "2026-05-05",
      },
      leg: leg("2026-05-05T00:30:00+03:00"),
    };

    expect(getFlightSearchDate(flight)).toBe("20260505");
  });

  it("uses the first leg for multi-leg flights", () => {
    const flight: IMultiLegFlight = {
      id: "SU100",
      routeType: "MultiLeg",
      flyingTime: "",
      operatingBy: {},
      status: "Scheduled",
      flightId: {
        carrier: "SU",
        flightNumber: "0100",
        suffix: "",
        date: "20260504",
      },
      legs: [
        leg("2026-05-05T23:30:00+03:00"),
        leg("2026-05-06T01:30:00+03:00"),
      ],
    };

    expect(getFlightSearchDate(flight)).toBe("20260505");
  });

  it("falls back to dateLT and then flightId.date when leg date is unavailable", () => {
    const flight: IDirectFlight = {
      id: "SU42",
      routeType: "Direct",
      flyingTime: "",
      operatingBy: {},
      status: "Scheduled",
      flightId: {
        carrier: "SU",
        flightNumber: "0042",
        suffix: "",
        date: "2026-05-04",
        dateLT: "2026-05-05",
      },
      leg: leg("10:00"),
    };

    expect(getFlightSearchDate(flight)).toBe("20260505");

    const { dateLT: _dateLT, ...flightIdWithoutDateLt } = flight.flightId;
    const withoutDateLt: IDirectFlight = {
      ...flight,
      flightId: flightIdWithoutDateLt,
    };

    expect(getFlightSearchDate(withoutDateLt)).toBe("20260504");
  });
});
