/**
 * Season date matching — MM-DD ranges, including year-wrap
 * (e.g. Peak 11-01 → 03-31). `durations[]` wins when present so
 * multi-range seasons from Settings → Seasons resolve the same way
 * on cost lookup as they do on the matrix UI.
 */
export function mmddInRange(mmdd: string, start: string, end: string): boolean {
  return start <= end ? mmdd >= start && mmdd <= end : mmdd >= start || mmdd <= end;
}

export interface SeasonDateRange {
  id: string;
  start_date?: string | null;
  end_date?: string | null;
  durations?: { start: string; end: string }[] | null;
  is_active?: boolean;
}

export function seasonMatchesDate(season: SeasonDateRange, isoDate: string): boolean {
  if (season.is_active === false) return false;
  if (!isoDate || isoDate.length < 10) return false;
  const mmdd = isoDate.substring(5); // YYYY-MM-DD → MM-DD
  if (!/^\d{2}-\d{2}$/.test(mmdd)) return false;
  const ranges =
    season.durations && season.durations.length > 0
      ? season.durations
      : season.start_date && season.end_date
        ? [{ start: season.start_date, end: season.end_date }]
        : [];
  return ranges.some((r) => r.start && r.end && mmddInRange(mmdd, r.start, r.end));
}

export function findMatchingSeasonId(
  seasons: SeasonDateRange[],
  isoDate: string | undefined | null,
): string | null {
  if (!isoDate) return null;
  for (const season of seasons) {
    if (seasonMatchesDate(season, isoDate)) return season.id;
  }
  return null;
}
