import type { IFlightLeg, ISimpleFlight } from "./types.js";

function compactDate(value: string | undefined): string | null {
  if (!value) return null;
  if (/^\d{8}$/.test(value)) return value;

  const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(value);
  if (!match) return null;

  return `${match[1]}${match[2]}${match[3]}`;
}

function getFirstLeg(flight: ISimpleFlight): IFlightLeg | null {
  if (flight.routeType === "Direct") return flight.leg;
  return flight.legs[0] ?? null;
}

/**
 * Angular's FlightDateUtils.getFlightDate derives the details URL date from
 * the first leg's scheduled local departure date, not from flightId.date.
 * Overnight flights can have flightId.date set to the previous backend
 * service day while dateLT / scheduled local departure belongs to the board
 * day the user clicked.
 */
export function getFlightSearchDate(flight: ISimpleFlight): string {
  const firstLeg = getFirstLeg(flight);

  return (
    compactDate(firstLeg?.departure.times.scheduledDeparture.local) ??
    compactDate(flight.flightId.dateLT) ??
    compactDate(flight.flightId.date) ??
    flight.flightId.date.replace(/-/g, "")
  );
}
