/**
 * Shared date-window guard for Online-Board routes per TZ §4.1.2 ¶3-4.
 *
 * Out-of-window dates redirect to the Online-Board start page instead of 404.
 * Parse failures (malformed URLs) continue to produce 404 via existing logic.
 */

import { isInBoardWindow } from "@/shared/dateWindow.js";

/**
 * Returns the redirect target path when the given yyyymmdd date falls outside
 * the Online-Board [-1, +14] day window. Returns null to allow normal render.
 *
 * Only called after a successful URL parse — malformed dates never reach here.
 */
export function boardDateRedirect(locale: string, yyyymmdd: string): string | null {
  if (!isInBoardWindow(yyyymmdd)) return `/${locale}/onlineboard`;
  return null;
}

function hhmmToMinutes(value: string): number | null {
  if (!/^\d{4}$/.test(value)) return null;
  const hours = Number(value.slice(0, 2));
  const minutes = Number(value.slice(2, 4));
  if (hours === 24 && minutes === 0) return 24 * 60;
  if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null;
  return hours * 60 + minutes;
}

/**
 * Angular parity for Online-Board date + optional `Время рейса` URL guards.
 *
 * A missing time range is valid. When a range is present, both ends must be
 * valid HHmm values and `timeFrom` must be strictly before `timeTo`.
 * `2400` is accepted as the upper bound, matching Angular/moment behavior.
 */
export function boardSearchRedirect(
  locale: string,
  params: { date: string; timeFrom?: string; timeTo?: string },
): string | null {
  const dateRedirect = boardDateRedirect(locale, params.date);
  if (dateRedirect) return dateRedirect;

  const hasFrom = params.timeFrom !== undefined;
  const hasTo = params.timeTo !== undefined;
  if (!hasFrom && !hasTo) return null;
  if (!hasFrom || !hasTo) return `/${locale}/onlineboard`;

  const timeFrom = params.timeFrom;
  const timeTo = params.timeTo;
  if (timeFrom === undefined || timeTo === undefined) {
    return `/${locale}/onlineboard`;
  }

  const from = hhmmToMinutes(timeFrom);
  const to = hhmmToMinutes(timeTo);
  if (from === null || to === null || from >= to) {
    return `/${locale}/onlineboard`;
  }

  return null;
}
