const AEROFLOT_SB_SEARCH_BASE = "https://www.aeroflot.ru/sb/app/ru-ru#/search";

const DEFAULT_SEARCH_PARAMS = {
  adults: "1",
  cabin: "economy",
  children: "0",
  infants: "0",
  autosearch: "Y",
} as const;

export function formatAeroflotRouteDate(value: string | undefined): string | null {
  if (!value) return null;
  const match = /^(\d{4})-?(\d{2})-?(\d{2})/.exec(value);
  if (!match) return null;
  return `${match[1]}${match[2]}${match[3]}`;
}

export interface AeroflotSbSearchUrlOptions {
  departure: string;
  arrival: string;
  date?: string | null | undefined;
  extraParams?: Record<string, string>;
}

export function buildAeroflotSbSearchUrl({
  departure,
  arrival,
  date,
  extraParams,
}: AeroflotSbSearchUrlOptions): string {
  const routes = date
    ? `${departure}.${date}.${arrival}`
    : `${departure}.${arrival}`;
  const params = new URLSearchParams({
    ...DEFAULT_SEARCH_PARAMS,
    routes,
    ...extraParams,
  });
  return `${AEROFLOT_SB_SEARCH_BASE}?${params.toString()}`;
}
