import { db } from "../db.ts";

export interface SeasonalEvent {
  id: string;
  name: string;
  description: string;
  theme: string;
  startDate: Date;
  endDate: Date;
  bonusMultiplier: number;
  specialGames: string[];
  rewards: SeasonalReward[];
  active: boolean;
}

export interface SeasonalReward {
  id: string;
  name: string;
  description: string;
  icon: string;
  requirement: number; // e.g., total wins needed
  bonus: number; // bonus amount
  currency: 'GC' | 'SC';
}

// Predefined seasonal events
const SEASONAL_EVENTS: Record<string, SeasonalEvent> = {
  halloween_2026: {
    id: 'halloween_2026',
    name: 'Spooky Spin Spectacular',
    description: 'Halloween-themed games with 2x bonus multiplier',
    theme: 'halloween',
    startDate: new Date('2026-10-01'),
    endDate: new Date('2026-10-31'),
    bonusMultiplier: 2.0,
    specialGames: ['haunted-mansion', 'pumpkin-patch', 'ghost-fortune'],
    rewards: [
      {
        id: 'halloween_wins_10',
        name: 'Trick or Treat',
        description: 'Win 10 games during Halloween',
        icon: '🎃',
        requirement: 10,
        bonus: 100,
        currency: 'SC',
      },
      {
        id: 'halloween_wins_25',
        name: 'Spooky Master',
        description: 'Win 25 games during Halloween',
        icon: '👻',
        requirement: 25,
        bonus: 500,
        currency: 'SC',
      },
    ],
    active: false,
  },
  christmas_2026: {
    id: 'christmas_2026',
    name: 'Festive Fortune',
    description: 'Christmas-themed games with 3x bonus multiplier',
    theme: 'christmas',
    startDate: new Date('2026-12-01'),
    endDate: new Date('2026-12-31'),
    bonusMultiplier: 3.0,
    specialGames: ['santa-sleigh', 'christmas-tree', 'gift-bonanza'],
    rewards: [
      {
        id: 'christmas_wins_15',
        name: 'Jolly Winner',
        description: 'Win 15 games during Christmas',
        icon: '🎅',
        requirement: 15,
        bonus: 250,
        currency: 'SC',
      },
      {
        id: 'christmas_wins_50',
        name: 'Holiday Champion',
        description: 'Win 50 games during Christmas',
        icon: '🎄',
        requirement: 50,
        bonus: 1000,
        currency: 'SC',
      },
    ],
    active: false,
  },
  new_year_2027: {
    id: 'new_year_2027',
    name: 'New Year New Luck',
    description: 'Fresh start with 2.5x bonus multiplier',
    theme: 'new_year',
    startDate: new Date('2027-01-01'),
    endDate: new Date('2027-01-31'),
    bonusMultiplier: 2.5,
    specialGames: ['lucky-7', 'fortune-wheel', 'golden-coins'],
    rewards: [
      {
        id: 'new_year_wins_20',
        name: 'Lucky Start',
        description: 'Win 20 games in January',
        icon: '🎆',
        requirement: 20,
        bonus: 300,
        currency: 'SC',
      },
    ],
    active: false,
  },
  summer_2026: {
    id: 'summer_2026',
    name: 'Summer Sizzle',
    description: 'Beach-themed games with 1.5x bonus multiplier',
    theme: 'summer',
    startDate: new Date('2026-06-21'),
    endDate: new Date('2026-09-22'),
    bonusMultiplier: 1.5,
    specialGames: ['beach-party', 'surfing-safari', 'tropical-paradise'],
    rewards: [
      {
        id: 'summer_wins_30',
        name: 'Summer Superstar',
        description: 'Win 30 games during summer',
        icon: '☀️',
        requirement: 30,
        bonus: 600,
        currency: 'SC',
      },
    ],
    active: false,
  },
};

export function getActiveEvents(): SeasonalEvent[] {
  const now = new Date();
  return Object.values(SEASONAL_EVENTS).filter(
    (event) => event.startDate <= now && event.endDate >= now
  );
}

export function getEventById(eventId: string): SeasonalEvent | undefined {
  return SEASONAL_EVENTS[eventId];
}

export function getAllEvents(): SeasonalEvent[] {
  return Object.values(SEASONAL_EVENTS);
}

export function getEventBonusMultiplier(eventId: string): number {
  const event = SEASONAL_EVENTS[eventId];
  return event ? event.bonusMultiplier : 1.0;
}

export async function getPlayerEventProgress(userId: number, eventId: string) {
  const event = SEASONAL_EVENTS[eventId];
  if (!event) return null;

  // Get player wins during event period
  const wins = await db.raw(
    `SELECT COUNT(*) as total_wins, SUM(amount) as total_winnings
     FROM transactions 
     WHERE userId = ? AND type = 'game_win' 
     AND createdAt >= ? AND createdAt <= ?`,
    [userId, event.startDate.toISOString(), event.endDate.toISOString()]
  );

  const totalWins = wins[0]?.total_wins || 0;
  const totalWinnings = wins[0]?.total_winnings || 0;

  // Calculate rewards earned
  const earnedRewards = event.rewards.filter((reward) => totalWins >= reward.requirement);

  return {
    eventId,
    eventName: event.name,
    totalWins,
    totalWinnings,
    earnedRewards,
    progress: (totalWins / (event.rewards[event.rewards.length - 1]?.requirement || 1)) * 100,
  };
}

export async function claimEventReward(userId: number, eventId: string, rewardId: string) {
  const event = SEASONAL_EVENTS[eventId];
  if (!event) return { success: false, message: 'Event not found' };

  const reward = event.rewards.find((r) => r.id === rewardId);
  if (!reward) return { success: false, message: 'Reward not found' };

  // Check if player qualifies
  const progress = await getPlayerEventProgress(userId, eventId);
  if (!progress || !progress.earnedRewards.find((r) => r.id === rewardId)) {
    return { success: false, message: 'Player does not qualify for this reward' };
  }

  // Credit reward (simplified - in production would track claimed rewards)
  return {
    success: true,
    message: `Claimed ${reward.name}!`,
    bonus: reward.bonus,
    currency: reward.currency,
  };
}
