/**
 * Profile Badges Service
 * Manages achievement badges, unlock conditions, and animations
 */

import { db } from './db.ts';
import { users } from '../drizzle/schema.ts';

export interface Badge {
  id: string;
  name: string;
  description: string;
  icon: string;
  rarity: 'common' | 'uncommon' | 'rare' | 'epic' | 'legendary';
  category: 'gameplay' | 'social' | 'vip' | 'special';
  unlockCondition: string;
  rewardAmount: number;
  animationType: 'pop' | 'slide' | 'bounce' | 'spin' | 'glow';
}

export interface UserBadge {
  badgeId: string;
  userId: string;
  unlockedAt: Date;
  progress: number;
  maxProgress: number;
}

// All available badges
const BADGES: Record<string, Badge> = {
  first_spin: {
    id: 'first_spin',
    name: 'First Spin',
    description: 'Play your first slot game',
    icon: '🎰',
    rarity: 'common',
    category: 'gameplay',
    unlockCondition: 'totalGamesPlayed >= 1',
    rewardAmount: 10,
    animationType: 'pop',
  },
  hundred_spins: {
    id: 'hundred_spins',
    name: 'Spin Master',
    description: 'Play 100 slot games',
    icon: '🎯',
    rarity: 'uncommon',
    category: 'gameplay',
    unlockCondition: 'totalGamesPlayed >= 100',
    rewardAmount: 50,
    animationType: 'bounce',
  },
  thousand_spins: {
    id: 'thousand_spins',
    name: 'Legendary Spinner',
    description: 'Play 1000 slot games',
    icon: '👑',
    rarity: 'rare',
    category: 'gameplay',
    unlockCondition: 'totalGamesPlayed >= 1000',
    rewardAmount: 200,
    animationType: 'glow',
  },
  big_winner: {
    id: 'big_winner',
    name: 'Big Winner',
    description: 'Win 1000 SC in a single spin',
    icon: '💰',
    rarity: 'rare',
    category: 'gameplay',
    unlockCondition: 'biggestWin >= 1000',
    rewardAmount: 150,
    animationType: 'spin',
  },
  lucky_seven: {
    id: 'lucky_seven',
    name: 'Lucky Seven',
    description: 'Win 7 games in a row',
    icon: '7️⃣',
    rarity: 'uncommon',
    category: 'gameplay',
    unlockCondition: 'winStreak >= 7',
    rewardAmount: 75,
    animationType: 'bounce',
  },
  bankroll_builder: {
    id: 'bankroll_builder',
    name: 'Bankroll Builder',
    description: 'Accumulate 10,000 SC in winnings',
    icon: '🏦',
    rarity: 'rare',
    category: 'gameplay',
    unlockCondition: 'totalWinnings >= 10000',
    rewardAmount: 250,
    animationType: 'slide',
  },
  social_butterfly: {
    id: 'social_butterfly',
    name: 'Social Butterfly',
    description: 'Share your profile 5 times',
    icon: '🦋',
    rarity: 'uncommon',
    category: 'social',
    unlockCondition: 'totalShares >= 5',
    rewardAmount: 50,
    animationType: 'pop',
  },
  referral_master: {
    id: 'referral_master',
    name: 'Referral Master',
    description: 'Successfully refer 5 friends',
    icon: '🎁',
    rarity: 'rare',
    category: 'social',
    unlockCondition: 'totalReferrals >= 5',
    rewardAmount: 200,
    animationType: 'glow',
  },
  vip_bronze: {
    id: 'vip_bronze',
    name: 'VIP Bronze',
    description: 'Reach VIP Bronze tier',
    icon: '🥉',
    rarity: 'uncommon',
    category: 'vip',
    unlockCondition: 'vipTier === "bronze"',
    rewardAmount: 100,
    animationType: 'slide',
  },
  vip_gold: {
    id: 'vip_gold',
    name: 'VIP Gold',
    description: 'Reach VIP Gold tier',
    icon: '🥇',
    rarity: 'epic',
    category: 'vip',
    unlockCondition: 'vipTier === "gold"',
    rewardAmount: 300,
    animationType: 'glow',
  },
  vip_platinum: {
    id: 'vip_platinum',
    name: 'VIP Platinum',
    description: 'Reach VIP Platinum tier',
    icon: '💎',
    rarity: 'legendary',
    category: 'vip',
    unlockCondition: 'vipTier === "platinum"',
    rewardAmount: 500,
    animationType: 'spin',
  },
  daily_player: {
    id: 'daily_player',
    name: 'Daily Player',
    description: 'Play 7 days in a row',
    icon: '📅',
    rarity: 'uncommon',
    category: 'gameplay',
    unlockCondition: 'loginStreak >= 7',
    rewardAmount: 75,
    animationType: 'bounce',
  },
  night_owl: {
    id: 'night_owl',
    name: 'Night Owl',
    description: 'Play between midnight and 6 AM',
    icon: '🦉',
    rarity: 'uncommon',
    category: 'special',
    unlockCondition: 'playedAtNight === true',
    rewardAmount: 50,
    animationType: 'pop',
  },
  weekend_warrior: {
    id: 'weekend_warrior',
    name: 'Weekend Warrior',
    description: 'Play for 5 hours on a weekend',
    icon: '⚔️',
    rarity: 'uncommon',
    category: 'gameplay',
    unlockCondition: 'weekendPlayTime >= 5',
    rewardAmount: 100,
    animationType: 'bounce',
  },
};

/**
 * Get all available badges
 */
export async function getAllBadges(): Promise<Badge[]> {
  try {
    return Object.values(BADGES);
  } catch (error) {
    console.error('[ProfileBadges] Error fetching all badges:', error);
    return [];
  }
}

/**
 * Get user's unlocked badges
 */
export async function getUserBadges(userId: string): Promise<UserBadge[]> {
  try {
    const database = await db();
    if (!database) return [];

    // Mock data - in production, query from database
    const userBadges: UserBadge[] = [
      {
        badgeId: 'first_spin',
        userId,
        unlockedAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
        progress: 1,
        maxProgress: 1,
      },
      {
        badgeId: 'hundred_spins',
        userId,
        unlockedAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000),
        progress: 100,
        maxProgress: 100,
      },
      {
        badgeId: 'social_butterfly',
        userId,
        unlockedAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
        progress: 5,
        maxProgress: 5,
      },
    ];

    console.log(`[ProfileBadges] Retrieved ${userBadges.length} badges for user ${userId}`);
    return userBadges;
  } catch (error) {
    console.error('[ProfileBadges] Error fetching user badges:', error);
    return [];
  }
}

/**
 * Check if user should unlock a badge
 */
export async function checkBadgeUnlock(userId: string, stats: any): Promise<string[]> {
  try {
    const unlockedBadges: string[] = [];

    // Check each badge condition
    for (const [badgeId, badge] of Object.entries(BADGES)) {
      // Simple condition evaluation (in production, use more robust evaluation)
      if (badgeId === 'first_spin' && stats.totalGamesPlayed >= 1) {
        unlockedBadges.push(badgeId);
      } else if (badgeId === 'hundred_spins' && stats.totalGamesPlayed >= 100) {
        unlockedBadges.push(badgeId);
      } else if (badgeId === 'thousand_spins' && stats.totalGamesPlayed >= 1000) {
        unlockedBadges.push(badgeId);
      } else if (badgeId === 'big_winner' && stats.biggestWin >= 1000) {
        unlockedBadges.push(badgeId);
      } else if (badgeId === 'bankroll_builder' && stats.totalWinnings >= 10000) {
        unlockedBadges.push(badgeId);
      }
    }

    console.log(`[ProfileBadges] Checked ${Object.keys(BADGES).length} badges for user ${userId}, unlocked: ${unlockedBadges.length}`);
    return unlockedBadges;
  } catch (error) {
    console.error('[ProfileBadges] Error checking badge unlock:', error);
    return [];
  }
}

/**
 * Get badge details
 */
export function getBadgeDetails(badgeId: string): Badge | null {
  return BADGES[badgeId] || null;
}

/**
 * Get badges by category
 */
export async function getBadgesByCategory(category: 'gameplay' | 'social' | 'vip' | 'special'): Promise<Badge[]> {
  try {
    return Object.values(BADGES).filter((badge) => badge.category === category);
  } catch (error) {
    console.error('[ProfileBadges] Error fetching badges by category:', error);
    return [];
  }
}

/**
 * Get badges by rarity
 */
export async function getBadgesByRarity(rarity: 'common' | 'uncommon' | 'rare' | 'epic' | 'legendary'): Promise<Badge[]> {
  try {
    return Object.values(BADGES).filter((badge) => badge.rarity === rarity);
  } catch (error) {
    console.error('[ProfileBadges] Error fetching badges by rarity:', error);
    return [];
  }
}

/**
 * Calculate total badge rewards
 */
export async function calculateBadgeRewards(userBadges: UserBadge[]): Promise<number> {
  try {
    let totalRewards = 0;

    for (const userBadge of userBadges) {
      const badge = BADGES[userBadge.badgeId];
      if (badge) {
        totalRewards += badge.rewardAmount;
      }
    }

    return totalRewards;
  } catch (error) {
    console.error('[ProfileBadges] Error calculating badge rewards:', error);
    return 0;
  }
}

/**
 * Get badge unlock animation
 */
export function getBadgeAnimation(badgeId: string): { type: string; duration: number; delay: number } {
  const badge = BADGES[badgeId];
  if (!badge) {
    return { type: 'pop', duration: 500, delay: 0 };
  }

  const animationDurations: Record<string, number> = {
    pop: 600,
    slide: 800,
    bounce: 1000,
    spin: 1200,
    glow: 1500,
  };

  return {
    type: badge.animationType,
    duration: animationDurations[badge.animationType] || 600,
    delay: 100,
  };
}
