const seasonalEventCache = new Map();
const CACHE_TTL = 60000;

async function getActiveSeasonalEvents(supabase, guildId) {
  const now = Date.now();
  const cacheKey = guildId;
  const cached = seasonalEventCache.get(cacheKey);

  if (cached && (now - cached.timestamp < CACHE_TTL)) {
    return cached.events;
  }

  try {
    const currentTime = new Date().toISOString();
    const { data: events, error } = await supabase
      .from('seasonal_events')
      .select('*')
      .eq('guild_id', guildId)
      .lte('start_date', currentTime)
      .gte('end_date', currentTime);

    if (error) {
      seasonalEventCache.set(cacheKey, { events: [], timestamp: now });
      return [];
    }

    const activeEvents = events || [];
    seasonalEventCache.set(cacheKey, { events: activeEvents, timestamp: now });
    return activeEvents;
  } catch (e) {
    return [];
  }
}

function getSeasonalMultiplier(events) {
  if (!events || events.length === 0) return 1;
  
  let highestMultiplier = 1;
  for (const event of events) {
    if (event.xp_multiplier && event.xp_multiplier > highestMultiplier) {
      highestMultiplier = event.xp_multiplier;
    }
  }
  return highestMultiplier;
}

function getSeasonalBonusCoins(events) {
  if (!events || events.length === 0) return 0;
  
  let totalBonus = 0;
  for (const event of events) {
    if (event.bonus_coins) {
      totalBonus += event.bonus_coins;
    }
  }
  return totalBonus;
}

function clearSeasonalCache(guildId) {
  if (guildId) {
    seasonalEventCache.delete(guildId);
  } else {
    seasonalEventCache.clear();
  }
}

module.exports = {
  getActiveSeasonalEvents,
  getSeasonalMultiplier,
  getSeasonalBonusCoins,
  clearSeasonalCache
};
