import axios from 'axios';
import { API_URL } from 'src/constants';
import { API } from 'src/types';

const SERVER_LIST_URL = API_URL + '/' + API.GET_SERVERS;
const TIMEOUT = 1500;

const fetchWithTimeout = (url: string, timeout = TIMEOUT) => {
  return axios.get(url, { timeout, headers: {'Cache-Control': 'no-cache'} });
};

const testServerSpeed = async (serverUrl: string) => {
  const startTime = Date.now();
  try {
    await fetchWithTimeout(serverUrl);
    const endTime = Date.now();
    return endTime - startTime;
  } catch (error) {
    console.error(`Error fetching ${serverUrl}:`, error);
    return TIMEOUT;
  }
};

export const determineFastestServer = async () => {
  try {
    const response = await axios.get(SERVER_LIST_URL);
    const servers = response.data?.maps;

    const speedTests = await Promise.allSettled(
      servers?.map((server: string) => testServerSpeed(server + '/tiles_osm/2/2/2'))
    );

    let fastestServer = null;
    let fastestTime = TIMEOUT;

    speedTests.forEach((result, index) => {
      if (result.status === 'fulfilled' && result.value < fastestTime) {
        fastestTime = result.value;
        fastestServer = servers[index];
      }
    });

    if (fastestServer) {
      return fastestServer;
    } else {
      return null;
    }
  } catch (error) {
    console.error('Error determining fastest server:', error);
    throw error;
  }
};
