import { FootballApiMatch, FootballApiResponse } from '../types';
import { logger } from './logger';

const BASE_URL = process.env.FOOTBALL_API_BASE_URL ?? 'https://api.football-data.org/v4';
const API_KEY = process.env.FOOTBALL_API_KEY ?? '';

// WM 2026 Competition Code bei football-data.org
const WC_2026_CODE = 'WC';

/**
 * Rate limiting: Free tier = 10 Requests/Minute
 * Wir tracken den letzten Request-Zeitpunkt
 */
const requestQueue: Array<() => void> = [];
let lastRequestTime = 0;
const MIN_REQUEST_INTERVAL = 6100; // ~10 req/min with safety buffer

const throttledFetch = async (url: string): Promise<Response> => {
  const now = Date.now();
  const timeSinceLastRequest = now - lastRequestTime;

  if (timeSinceLastRequest < MIN_REQUEST_INTERVAL) {
    const waitTime = MIN_REQUEST_INTERVAL - timeSinceLastRequest;
    logger.debug(`Rate limiting: waiting ${waitTime}ms`);
    await new Promise(r => setTimeout(r, waitTime));
  }

  lastRequestTime = Date.now();

  try {
    const response = await fetch(url, {
      headers: {
        'X-Auth-Token': API_KEY,
        'Accept': 'application/json',
      },
    });
    return response;
  } catch (error: unknown) {
    const msg = error instanceof Error ? error.message : String(error);
    logger.error('football-data.org fetch failed', { url, error: msg });
    throw new Error(`Netzwerkfehler beim Abruf von football-data.org: ${msg}`);
  }
};

/**
 * Alle Spiele der WM 2026 von football-data.org abrufen
 */
export const fetchAllMatches = async (): Promise<FootballApiMatch[]> => {
  const url = `${BASE_URL}/competitions/${WC_2026_CODE}/matches`;

  logger.info('Fetching WC 2026 matches from football-data.org');

  const response = await throttledFetch(url);

  if (response.status === 429) {
    throw new Error('football-data.org rate limit exceeded');
  }

  if (!response.ok) {
    const body = await response.text();
    throw new Error(
      `football-data.org API error: ${response.status} ${response.statusText} – ${body}`
    );
  }

  const data = (await response.json()) as FootballApiResponse;

  logger.info(`Fetched ${data.matches.length} matches from football-data.org`);
  return data.matches;
};

/**
 * Nur FINISHED Spiele abrufen (für Punkte-Berechnung)
 */
export const fetchFinishedMatches = async (): Promise<FootballApiMatch[]> => {
  const url = `${BASE_URL}/competitions/${WC_2026_CODE}/matches?status=FINISHED`;
  const response = await throttledFetch(url);

  if (!response.ok) {
    throw new Error(`football-data.org API error: ${response.status}`);
  }

  const data = (await response.json()) as FootballApiResponse;
  return data.matches;
};

/**
 * Ein einzelnes Spiel abrufen (für Live-Updates)
 */
export const fetchMatch = async (matchId: number): Promise<FootballApiMatch> => {
  const url = `${BASE_URL}/matches/${matchId}`;
  const response = await throttledFetch(url);

  if (!response.ok) {
    throw new Error(`football-data.org API error: ${response.status}`);
  }

  const data = (await response.json()) as { match: FootballApiMatch };
  return data.match;
};
