import { Race, UserPreferences } from '../types';

/**
 * Apply preference-based filters to a list of races.
 *
 * Handles client-side filtering for:
 * - Multiple preferred racing types (the API only supports a single value)
 * - Multiple favorite tracks (the API only supports a single substring match)
 *
 * When no preferences are set, all races pass through unchanged.
 */
export function applyPreferenceFilters(
  races: Race[],
  prefs: UserPreferences | null,
): Race[] {
  if (!prefs) return races;

  let filtered = races;

  // Filter by racing types
  const racingTypes = prefs.preferred_racing_types;
  if (racingTypes && racingTypes.length > 0) {
    filtered = filtered.filter((r) => racingTypes.includes(r.racing_type));
  }

  // Filter by favorite tracks
  const tracks = prefs.favorite_tracks;
  if (tracks && tracks.length > 0) {
    filtered = filtered.filter((r) => tracks.includes(r.track));
  }

  return filtered;
}

/**
 * Check whether the user has any active feed filters configured.
 */
export function hasActiveFilters(prefs: UserPreferences | null): boolean {
  if (!prefs) return false;
  return (
    (prefs.preferred_racing_types?.length ?? 0) > 0 ||
    (prefs.favorite_tracks?.length ?? 0) > 0
  );
}

/**
 * Find the next upcoming race from a filtered race list.
 * Returns null when no matching races are found.
 */
export function findNextRace(races: Race[]): Race | null {
  const now = new Date();
  const upcoming = races
    .filter((r) => new Date(r.start_time).getTime() > now.getTime())
    .sort(
      (a, b) =>
        new Date(a.start_time).getTime() - new Date(b.start_time).getTime(),
    );
  return upcoming[0] ?? null;
}
