import { parseISO, subHours, isAfter, isBefore } from "date-fns";
import type { ISimpleFlight } from "../../../types.js";

/**
 * Buy Ticket button is visible when:
 * - flight is NOT Cancelled or InFlight
 * - now falls within [departure - maxHours, departure - minHours]
 */
export function canBuyTicket(
  flight: ISimpleFlight,
  now: Date,
  minHours: number,
  maxHours: number,
): boolean {
  if (flight.status === "Cancelled" || flight.status === "InFlight") return false;

  const leg = flight.routeType === "Direct" ? flight.leg : flight.legs[0];
  if (!leg) return false;

  const depUtc = leg.departure.times.scheduledDeparture.utc;
  if (!depUtc) return false;

  const departure = parseISO(depUtc);
  if (isNaN(departure.getTime())) return false;

  const showFrom = subHours(departure, maxHours);
  const showUntil = subHours(departure, minHours);

  return isAfter(now, showFrom) && isBefore(now, showUntil);
}
