/**
 * VIP Game Library Service
 * Manages exclusive games for each VIP tier
 */

import { db } from './db.ts';
import { users, casinoGames } from '../drizzle/schema.ts';
import { eq } from 'drizzle-orm';

export interface VIPExclusiveGame {
  id: string;
  name: string;
  description: string;
  tier: 'bronze' | 'silver' | 'gold' | 'platinum';
  rtp: number;
  minBet: number;
  maxBet: number;
  thumbnail: string;
  category: string;
  releaseDate: Date;
  features: string[];
}

// VIP Exclusive Games Database
const VIP_EXCLUSIVE_GAMES: VIPExclusiveGame[] = [
  // Bronze Tier Games
  {
    id: 'vip-bronze-1',
    name: 'Bronze Bonanza',
    description: 'Classic slots with bronze-themed symbols and steady payouts',
    tier: 'bronze',
    rtp: 94.5,
    minBet: 0.1,
    maxBet: 10,
    thumbnail: '/games/bronze-bonanza.png',
    category: 'slots',
    releaseDate: new Date('2024-01-01'),
    features: ['Free Spins', 'Wild Symbols', 'Bonus Rounds'],
  },
  {
    id: 'vip-bronze-2',
    name: 'Lucky Sevens VIP',
    description: 'VIP version of classic lucky sevens with enhanced multipliers',
    tier: 'bronze',
    rtp: 95.2,
    minBet: 0.1,
    maxBet: 15,
    thumbnail: '/games/lucky-sevens-vip.png',
    category: 'slots',
    releaseDate: new Date('2024-01-15'),
    features: ['Multipliers', 'Scatter Pays', 'Bonus Features'],
  },

  // Silver Tier Games
  {
    id: 'vip-silver-1',
    name: 'Silver Cascade',
    description: 'Cascading reels game with silver-themed premium symbols',
    tier: 'silver',
    rtp: 96.0,
    minBet: 0.2,
    maxBet: 25,
    thumbnail: '/games/silver-cascade.png',
    category: 'slots',
    releaseDate: new Date('2024-02-01'),
    features: ['Cascading Reels', 'Multiplier Boost', 'Free Spins'],
  },
  {
    id: 'vip-silver-2',
    name: 'Silver Vault',
    description: 'Treasure vault themed game with silver rewards',
    tier: 'silver',
    rtp: 95.8,
    minBet: 0.2,
    maxBet: 30,
    thumbnail: '/games/silver-vault.png',
    category: 'slots',
    releaseDate: new Date('2024-02-15'),
    features: ['Vault Bonus', 'Expanding Wilds', 'Mystery Symbols'],
  },
  {
    id: 'vip-silver-3',
    name: 'Silver Jackpot Rush',
    description: 'Fast-paced game with frequent jackpot opportunities',
    tier: 'silver',
    rtp: 96.2,
    minBet: 0.15,
    maxBet: 20,
    thumbnail: '/games/silver-jackpot-rush.png',
    category: 'slots',
    releaseDate: new Date('2024-02-28'),
    features: ['Progressive Jackpot', 'Quick Spins', 'Bonus Rounds'],
  },

  // Gold Tier Games
  {
    id: 'vip-gold-1',
    name: 'Golden Dragon',
    description: 'Legendary dragon-themed game with premium gold rewards',
    tier: 'gold',
    rtp: 96.5,
    minBet: 0.5,
    maxBet: 50,
    thumbnail: '/games/golden-dragon.png',
    category: 'slots',
    releaseDate: new Date('2024-03-01'),
    features: ['Dragon Wilds', 'Golden Spins', 'Multiplier Stacks'],
  },
  {
    id: 'vip-gold-2',
    name: 'Gold Rush Megaways',
    description: 'Megaways game with up to 117,649 ways to win',
    tier: 'gold',
    rtp: 96.8,
    minBet: 0.3,
    maxBet: 60,
    thumbnail: '/games/gold-rush-megaways.png',
    category: 'slots',
    releaseDate: new Date('2024-03-15'),
    features: ['Megaways', 'Cascading Wins', 'Bonus Spins'],
  },
  {
    id: 'vip-gold-3',
    name: 'Golden Pharaoh',
    description: 'Egyptian-themed premium game with golden treasures',
    tier: 'gold',
    rtp: 96.3,
    minBet: 0.4,
    maxBet: 55,
    thumbnail: '/games/golden-pharaoh.png',
    category: 'slots',
    releaseDate: new Date('2024-03-28'),
    features: ['Pharaoh Bonus', 'Golden Symbols', 'Free Spins'],
  },
  {
    id: 'vip-gold-4',
    name: 'Gold Vault Deluxe',
    description: 'Premium vault game with enhanced gold rewards',
    tier: 'gold',
    rtp: 97.0,
    minBet: 0.35,
    maxBet: 65,
    thumbnail: '/games/gold-vault-deluxe.png',
    category: 'slots',
    releaseDate: new Date('2024-04-10'),
    features: ['Vault Multipliers', 'Expanding Reels', 'Mega Spins'],
  },

  // Platinum Tier Games
  {
    id: 'vip-platinum-1',
    name: 'Platinum Infinity',
    description: 'Ultimate premium game with unlimited multiplier potential',
    tier: 'platinum',
    rtp: 97.5,
    minBet: 1.0,
    maxBet: 100,
    thumbnail: '/games/platinum-infinity.png',
    category: 'slots',
    releaseDate: new Date('2024-04-01'),
    features: ['Infinite Multipliers', 'Platinum Symbols', 'Mega Jackpot'],
  },
  {
    id: 'vip-platinum-2',
    name: 'Platinum Crown',
    description: 'Royal-themed game with exclusive platinum rewards',
    tier: 'platinum',
    rtp: 97.8,
    minBet: 0.8,
    maxBet: 120,
    thumbnail: '/games/platinum-crown.png',
    category: 'slots',
    releaseDate: new Date('2024-04-15'),
    features: ['Crown Bonus', 'Royal Multipliers', 'Exclusive Spins'],
  },
  {
    id: 'vip-platinum-3',
    name: 'Platinum Paradise',
    description: 'Paradise-themed game with maximum premium features',
    tier: 'platinum',
    rtp: 97.2,
    minBet: 0.9,
    maxBet: 150,
    thumbnail: '/games/platinum-paradise.png',
    category: 'slots',
    releaseDate: new Date('2024-04-28'),
    features: ['Paradise Wilds', 'Cascading Multipliers', 'Mega Bonus'],
  },
  {
    id: 'vip-platinum-4',
    name: 'Platinum Jackpot Elite',
    description: 'Elite game with the highest jackpot potential',
    tier: 'platinum',
    rtp: 98.0,
    minBet: 1.0,
    maxBet: 200,
    thumbnail: '/games/platinum-jackpot-elite.png',
    category: 'slots',
    releaseDate: new Date('2024-05-10'),
    features: ['Elite Jackpot', 'Maximum Multipliers', 'VIP Bonus'],
  },
  {
    id: 'vip-platinum-5',
    name: 'Platinum Legends',
    description: 'Legendary game exclusively for platinum VIP members',
    tier: 'platinum',
    rtp: 97.6,
    minBet: 0.95,
    maxBet: 180,
    thumbnail: '/games/platinum-legends.png',
    category: 'slots',
    releaseDate: new Date('2024-05-20'),
    features: ['Legend Symbols', 'Platinum Cascade', 'Exclusive Rewards'],
  },
];

/**
 * Get all VIP exclusive games
 */
export async function getAllVIPExclusiveGames(): Promise<VIPExclusiveGame[]> {
  return VIP_EXCLUSIVE_GAMES;
}

/**
 * Get VIP games for a specific tier
 */
export async function getVIPGamesByTier(tier: string): Promise<VIPExclusiveGame[]> {
  return VIP_EXCLUSIVE_GAMES.filter((game) => game.tier === tier);
}

/**
 * Get accessible VIP games for a player
 */
export async function getAccessibleVIPGames(userId: string): Promise<VIPExclusiveGame[]> {
  const database = await db();
  if (!database) return [];

  const user = await (database as any).query.users.findFirst({ where: { id: userId } });
  if (!user) return [];

  // Determine player tier
  const totalSpend = user.totalSpend || 0;
  let playerTier = 'bronze';

  if (totalSpend >= 15000) playerTier = 'platinum';
  else if (totalSpend >= 5000) playerTier = 'gold';
  else if (totalSpend >= 1000) playerTier = 'silver';

  // Get games for player's tier and all lower tiers
  const tierHierarchy: Record<string, string[]> = {
    bronze: ['bronze'],
    silver: ['bronze', 'silver'],
    gold: ['bronze', 'silver', 'gold'],
    platinum: ['bronze', 'silver', 'gold', 'platinum'],
  };

  const accessibleTiers = tierHierarchy[playerTier] || ['bronze'];
  return VIP_EXCLUSIVE_GAMES.filter((game) => accessibleTiers.includes(game.tier));
}

/**
 * Get VIP game by ID
 */
export async function getVIPGameById(gameId: string): Promise<VIPExclusiveGame | null> {
  return VIP_EXCLUSIVE_GAMES.find((game) => game.id === gameId) || null;
}

/**
 * Get VIP game statistics
 */
export async function getVIPGameStats() {
  const stats = {
    totalVIPGames: VIP_EXCLUSIVE_GAMES.length,
    gamesByTier: {
      bronze: VIP_EXCLUSIVE_GAMES.filter((g) => g.tier === 'bronze').length,
      silver: VIP_EXCLUSIVE_GAMES.filter((g) => g.tier === 'silver').length,
      gold: VIP_EXCLUSIVE_GAMES.filter((g) => g.tier === 'gold').length,
      platinum: VIP_EXCLUSIVE_GAMES.filter((g) => g.tier === 'platinum').length,
    },
    avgRTP: (VIP_EXCLUSIVE_GAMES.reduce((sum, g) => sum + g.rtp, 0) / VIP_EXCLUSIVE_GAMES.length).toFixed(2),
    latestGames: VIP_EXCLUSIVE_GAMES.sort((a, b) => b.releaseDate.getTime() - a.releaseDate.getTime()).slice(0, 5),
  };

  return stats;
}

/**
 * Get featured VIP games
 */
export async function getFeaturedVIPGames(limit: number = 10): Promise<VIPExclusiveGame[]> {
  return VIP_EXCLUSIVE_GAMES.sort((a, b) => b.releaseDate.getTime() - a.releaseDate.getTime()).slice(0, limit);
}

/**
 * Search VIP games
 */
export async function searchVIPGames(query: string): Promise<VIPExclusiveGame[]> {
  const lowerQuery = query.toLowerCase();
  return VIP_EXCLUSIVE_GAMES.filter(
    (game) =>
      game.name.toLowerCase().includes(lowerQuery) ||
      game.description.toLowerCase().includes(lowerQuery) ||
      game.features.some((f) => f.toLowerCase().includes(lowerQuery))
  );
}

/**
 * Get games by category
 */
export async function getVIPGamesByCategory(category: string): Promise<VIPExclusiveGame[]> {
  return VIP_EXCLUSIVE_GAMES.filter((game) => game.category === category);
}

/**
 * Get high RTP games
 */
export async function getHighRTPVIPGames(minRTP: number = 96.5): Promise<VIPExclusiveGame[]> {
  return VIP_EXCLUSIVE_GAMES.filter((game) => game.rtp >= minRTP).sort((a, b) => b.rtp - a.rtp);
}
