import { STATISTICS_ENDPOINT, STATISTICS_INTERVAL } from 'astro:env/server';
import { logger } from '@util/log.ts';

export let statistics: Awaited<ReturnType<typeof fetchStatistics>> | null = null;
if (STATISTICS_ENDPOINT) {
  statistics = await fetchStatistics().catch((_) => null);
  setInterval(
    () =>
      fetchStatistics()
        .catch((_) => null)
        .then((val) => (statistics = val)),
    STATISTICS_INTERVAL * 1000
  );
}

async function fetchStatistics() {
  logger.debug('fetching statistics');

  const response = (await fetch(STATISTICS_ENDPOINT!, {
    method: 'POST',
    body: JSON.stringify({
      categories: [{ name: 'PLAY_ONE_MINUTE' }, { name: 'PLAYER_KILLS' }, { name: 'DEATHS' }, { name: 'MOB_KILLS' }]
    })
  }).catch((e) => {
    logger.warn(
      {
        error: e
      },
      'could not fetch statistics'
    );
    throw e;
  })) as Response;

  type StatisticName = 'PLAY_ONE_MINUTE' | 'PLAYER_KILLS' | 'DEATHS' | 'MOB_KILLS';
  type ResponseData = {
    response: {
      playerStatistics: {
        playerName: string;
        statistics: { name: StatisticName; value: number }[];
      }[];
    };
  };
  const responseData: ResponseData = await response.json();

  let playtimeMinutes = 0;
  let playerKills = 0;
  let playerDeaths = 0;
  let mobKills = 0;
  for (const player of responseData.response.playerStatistics) {
    for (const statistic of player.statistics) {
      switch (statistic.name) {
        case 'PLAY_ONE_MINUTE':
          playtimeMinutes += statistic.value / 20 / 60;
          break;
        case 'PLAYER_KILLS':
          playerKills += statistic.value;
          break;
        case 'DEATHS':
          playerDeaths += statistic.value;
          break;
        case 'MOB_KILLS':
          mobKills += statistic.value;
          break;
      }
    }
  }

  return { playtimeMinutes, playerKills, playerDeaths, mobKills };
}
