import { parseIorDetail } from "./parseGameData.js";

/**
 * 全局运行时数据
 */
export const GLOBAL_DATA = {
  filtedLeagues: [],
  filtedGames: [],
  gamesMap: {},
  straightFixturesVersion: 0,
  straightFixturesCount: 0,
  specialFixturesVersion: 0,
  specialFixturesCount: 0,
  straightOddsVersion: 0,
  // straightOddsCount: 0,
  specialsOddsVersion: 0,
  // specialsOddsCount: 0,
  currencies: [],
  currenciesUpdatedAt: 0,
  requestErrorCount: 0,
  loopActive: false,
  loopResultTime: 0,
};

export const getCurrenciesInfo = () => {
  const { currencies, currenciesUpdatedAt } = GLOBAL_DATA;
  if (!currenciesUpdatedAt) {
    return Promise.reject({
      cause: 503,
      message: 'currencies data is not ready',
      data: { currenciesUpdatedAt },
    });
  }
  return Promise.resolve({ data: currencies, updatedAt: currenciesUpdatedAt });
}

export const findCurrencyInfo = (currencyCode) => {
  const code = currencyCode?.toUpperCase();
  const currencies = GLOBAL_DATA.currencies?.currencies ?? GLOBAL_DATA.currencies;
  if (!code || !Array.isArray(currencies)) {
    return null;
  }
  return currencies.find(currency => currency.code?.toUpperCase() === code) ?? null;
}

const normalizeIds = (ids) => {
  if (ids === undefined || ids === null || ids === '') {
    return [];
  }

  if (Array.isArray(ids)) {
    return ids.flatMap(normalizeIds);
  }

  return String(ids).split(',').map(id => id.trim()).filter(Boolean);
}

const getDateInTimezone = (offsetHours) => {
  const nowUTC = new Date();
  const targetTime = new Date(nowUTC.getTime() + offsetHours * 60 * 60 * 1000);
  const year = targetTime.getUTCFullYear();
  const month = String(targetTime.getUTCMonth() + 1).padStart(2, '0');
  const day = String(targetTime.getUTCDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

const isEventAvailable = (event) => {
  if (!event?.starts) {
    return false;
  }

  const startsTime = new Date(event.starts).getTime();
  if (!Number.isFinite(startsTime)) {
    return false;
  }

  const todayEndTime = new Date(`${getDateInTimezone(-4)} 23:59:59 GMT-4`).getTime();
  const tomorrowEndTime = todayEndTime + 24 * 60 * 60 * 1000;
  return startsTime >= Date.now() - 3 * 60 * 60 * 1000 && startsTime <= tomorrowEndTime;
}

const sortEventsByStarts = (events) => {
  return events.sort((a, b) => new Date(a.starts).getTime() - new Date(b.starts).getTime());
}

export const getEventsByIds = (ids) => {
  const normalizedIds = normalizeIds(ids);
  const { gamesMap={} } = GLOBAL_DATA;

  if (!normalizedIds.length) {
    return sortEventsByStarts(Object.values(gamesMap).filter(isEventAvailable));
  }

  return sortEventsByStarts(normalizedIds.map(id => gamesMap[id]).filter(Boolean).filter(isEventAvailable));
}

/**
 * 获取盘口详情
 * @param {*} ior
 * @param {*} id
 * @returns
 */
export const getIorInfo = async(ior, id) => {
  if (!id || !ior) {
    return Promise.reject({ cause: 400, message: 'id and ior are required', data: { id, ior } });
  }
  const { gamesMap } = GLOBAL_DATA;
  const iorInfo = parseIorDetail(ior, id, gamesMap);
  if (iorInfo.cause === 400) {
    return Promise.reject({ cause: 400, message: iorInfo.message, data: { id, ior } });
  }
  return Promise.resolve(iorInfo);
}
