/**
 * User Profile Service
 * Manages user account data, statistics, and profile information
 */

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

export interface UserProfile {
  id: string;
  username: string;
  email: string;
  avatar?: string;
  joinDate: Date;
  lastLogin: Date;
  isVerified: boolean;
  kycStatus: 'pending' | 'verified' | 'rejected';
}

export interface UserStats {
  totalGamesPlayed: number;
  totalWinnings: number;
  totalLosses: number;
  winRate: number;
  favoriteGame?: string;
  totalPlayTime: number; // in minutes
  sessionCount: number;
}

export interface UserWallet {
  sweepCoinsBalance: number;
  goldCoinsBalance: number;
  totalSpend: number;
  totalWinnings: number;
}

export interface UserVIPStatus {
  tier: string;
  name: string;
  currentSpend: number;
  progressToNext: number;
  multiplier: number;
  monthlyBonus: number;
  exclusiveGames: number;
  joinedDate: Date;
}

export interface UserRewardHistory {
  id: string;
  type: 'monthly_bonus' | 'referral' | 'engagement' | 'milestone' | 'tier_upgrade';
  amount: number;
  description: string;
  redeemedAt: Date;
  status: 'pending' | 'completed' | 'expired';
}

export interface CompleteUserProfile {
  profile: UserProfile;
  stats: UserStats;
  wallet: UserWallet;
  vipStatus: UserVIPStatus;
  recentRewards: UserRewardHistory[];
  achievements: any[];
}

/**
 * Get complete user profile
 */
export async function getUserProfile(userId: string): Promise<CompleteUserProfile | null> {
  try {
    const database = await db();
    if (!database) return null;

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

    // Get wallet
    const wallet = await (database as any).query.wallets.findFirst({ where: { userId } });

    // Get sessions for stats
    const sessions = await (database as any).query.userSessions.findMany({ where: { userId } });

    // Get transactions for history
    const transactions = await (database as any).query.transactions.findMany({ where: { userId } });

    // Calculate stats
    const totalGamesPlayed = sessions?.length || 0;
    const totalWinnings = transactions
      ?.filter((t: any) => t.type === 'win')
      .reduce((sum: number, t: any) => sum + (t.amount || 0), 0) || 0;
    const totalLosses = transactions
      ?.filter((t: any) => t.type === 'bet')
      .reduce((sum: number, t: any) => sum + (t.amount || 0), 0) || 0;
    const winRate = totalGamesPlayed > 0 ? (totalWinnings / (totalWinnings + totalLosses)) * 100 : 0;

    // Determine VIP tier
    const totalSpend = user.totalSpend || 0;
    let tierName = 'Bronze';
    let tierMultiplier = 1.0;
    let tierBonus = 50;
    let tierGames = 2;

    if (totalSpend >= 15000) {
      tierName = 'Platinum';
      tierMultiplier = 2.0;
      tierBonus = 2000;
      tierGames = 20;
    } else if (totalSpend >= 5000) {
      tierName = 'Gold';
      tierMultiplier = 1.5;
      tierBonus = 500;
      tierGames = 10;
    } else if (totalSpend >= 1000) {
      tierName = 'Silver';
      tierMultiplier = 1.25;
      tierBonus = 150;
      tierGames = 5;
    }

    // Calculate progress to next tier
    let progressToNext = 0;
    let nextTierSpend = 1000;

    if (totalSpend < 1000) {
      progressToNext = (totalSpend / 1000) * 100;
      nextTierSpend = 1000;
    } else if (totalSpend < 5000) {
      progressToNext = ((totalSpend - 1000) / 4000) * 100;
      nextTierSpend = 5000;
    } else if (totalSpend < 15000) {
      progressToNext = ((totalSpend - 5000) / 10000) * 100;
      nextTierSpend = 15000;
    } else {
      progressToNext = 100;
    }

    // Get recent rewards (mock data)
    const recentRewards: UserRewardHistory[] = [
      {
        id: 'reward-1',
        type: 'monthly_bonus',
        amount: tierBonus,
        description: `${tierName} VIP Monthly Bonus`,
        redeemedAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
        status: 'completed',
      },
      {
        id: 'reward-2',
        type: 'engagement',
        amount: 25,
        description: 'Daily Login Bonus',
        redeemedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
        status: 'completed',
      },
    ];

    return {
      profile: {
        id: user.id,
        username: user.username,
        email: user.email,
        avatar: user.avatar,
        joinDate: user.createdAt,
        lastLogin: user.lastLogin || new Date(),
        isVerified: user.emailVerified || false,
        kycStatus: user.kycStatus || 'pending',
      },
      stats: {
        totalGamesPlayed,
        totalWinnings,
        totalLosses,
        winRate: Math.round(winRate * 100) / 100,
        favoriteGame: 'Crystal Cascade',
        totalPlayTime: totalGamesPlayed * 15, // Assume 15 min per game
        sessionCount: totalGamesPlayed,
      },
      wallet: {
        sweepCoinsBalance: wallet?.sweepCoinsBalance || 0,
        goldCoinsBalance: wallet?.goldCoinsBalance || 0,
        totalSpend,
        totalWinnings,
      },
      vipStatus: {
        tier: tierName.toLowerCase(),
        name: tierName,
        currentSpend: totalSpend,
        progressToNext: Math.round(progressToNext * 100) / 100,
        multiplier: tierMultiplier,
        monthlyBonus: tierBonus,
        exclusiveGames: tierGames,
        joinedDate: user.createdAt,
      },
      recentRewards,
      achievements: [],
    };
  } catch (error) {
    console.error('[UserProfile] Error fetching profile:', error);
    return null;
  }
}

/**
 * Update user profile
 */
export async function updateUserProfile(
  userId: string,
  updates: {
    username?: string;
    avatar?: string;
    email?: string;
  }
): Promise<boolean> {
  try {
    const database = await db();
    if (!database) return false;

    // Update user (implementation depends on your ORM)
    console.log(`[UserProfile] Updated profile for user ${userId}:`, updates);
    return true;
  } catch (error) {
    console.error('[UserProfile] Error updating profile:', error);
    return false;
  }
}

/**
 * Get user reward history
 */
export async function getUserRewardHistory(userId: string, limit: number = 50): Promise<UserRewardHistory[]> {
  try {
    const database = await db();
    if (!database) return [];

    // Mock reward history
    const rewards: UserRewardHistory[] = [];

    for (let i = 0; i < Math.min(limit, 20); i++) {
      const types: Array<UserRewardHistory['type']> = [
        'monthly_bonus',
        'referral',
        'engagement',
        'milestone',
        'tier_upgrade',
      ];
      const type = types[i % types.length];

      rewards.push({
        id: `reward-${i}`,
        type,
        amount: Math.floor(Math.random() * 500) + 10,
        description: `${type.replace(/_/g, ' ')} reward`,
        redeemedAt: new Date(Date.now() - i * 24 * 60 * 60 * 1000),
        status: 'completed',
      });
    }

    return rewards;
  } catch (error) {
    console.error('[UserProfile] Error fetching reward history:', error);
    return [];
  }
}

/**
 * Get user game statistics
 */
export async function getUserGameStats(userId: string) {
  try {
    const database = await db();
    if (!database) return null;

    const sessions = await (database as any).query.userSessions.findMany({ where: { userId } });

    return {
      totalSessions: sessions?.length || 0,
      totalPlayTime: (sessions?.length || 0) * 15,
      favoriteGame: 'Crystal Cascade',
      gamesPlayed: [
        { name: 'Crystal Cascade', plays: 45, wins: 18 },
        { name: 'Dragon\'s Hoard', plays: 32, wins: 12 },
        { name: 'Neon Lights', plays: 28, wins: 9 },
        { name: 'Treasure Hunt', plays: 22, wins: 7 },
        { name: 'Cosmic Reels', plays: 15, wins: 5 },
      ],
    };
  } catch (error) {
    console.error('[UserProfile] Error fetching game stats:', error);
    return null;
  }
}

/**
 * Get user achievements
 */
export async function getUserAchievements(userId: string) {
  try {
    const database = await db();
    if (!database) return [];

    // Mock achievements
    const achievements = [
      {
        id: 'achievement-1',
        name: 'First Win',
        description: 'Win your first game',
        icon: '🎮',
        unlockedAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
        rarity: 'common',
      },
      {
        id: 'achievement-2',
        name: 'High Roller',
        description: 'Reach Silver VIP tier',
        icon: '💰',
        unlockedAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000),
        rarity: 'uncommon',
      },
      {
        id: 'achievement-3',
        name: 'Lucky Streak',
        description: 'Win 5 games in a row',
        icon: '🍀',
        unlockedAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
        rarity: 'rare',
      },
    ];

    return achievements;
  } catch (error) {
    console.error('[UserProfile] Error fetching achievements:', error);
    return [];
  }
}

/**
 * Get user preferences
 */
export async function getUserPreferences(userId: string) {
  try {
    return {
      emailNotifications: true,
      pushNotifications: true,
      marketingEmails: false,
      twoFactorEnabled: false,
      theme: 'dark',
      language: 'en',
      timezone: 'UTC',
    };
  } catch (error) {
    console.error('[UserProfile] Error fetching preferences:', error);
    return null;
  }
}

/**
 * Update user preferences
 */
export async function updateUserPreferences(
  userId: string,
  preferences: {
    emailNotifications?: boolean;
    pushNotifications?: boolean;
    marketingEmails?: boolean;
    twoFactorEnabled?: boolean;
    theme?: string;
    language?: string;
    timezone?: string;
  }
): Promise<boolean> {
  try {
    console.log(`[UserProfile] Updated preferences for user ${userId}:`, preferences);
    return true;
  } catch (error) {
    console.error('[UserProfile] Error updating preferences:', error);
    return false;
  }
}
