/**
 * VIP Notifications & Real-time Analytics Service
 * Handles real-time notifications, tier upgrades, and reward alerts
 */

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

export interface VIPNotification {
  id: string;
  userId: string;
  type: 'tier_upgrade' | 'monthly_bonus' | 'reward_earned' | 'exclusive_game' | 'milestone';
  title: string;
  message: string;
  amount?: number;
  tier?: string;
  read: boolean;
  createdAt: Date;
}

// In-memory notification store (in production, use database)
const notificationStore = new Map<string, VIPNotification[]>();

/**
 * Create VIP notification
 */
export async function createVIPNotification(
  userId: string,
  type: VIPNotification['type'],
  title: string,
  message: string,
  amount?: number,
  tier?: string
): Promise<VIPNotification> {
  const notification: VIPNotification = {
    id: `notif-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
    userId,
    type,
    title,
    message,
    amount,
    tier,
    read: false,
    createdAt: new Date(),
  };

  if (!notificationStore.has(userId)) {
    notificationStore.set(userId, []);
  }

  notificationStore.get(userId)!.push(notification);

  // Keep only last 100 notifications per user
  const userNotifications = notificationStore.get(userId)!;
  if (userNotifications.length > 100) {
    userNotifications.shift();
  }

  return notification;
}

/**
 * Get user notifications
 */
export async function getUserNotifications(userId: string, limit: number = 50): Promise<VIPNotification[]> {
  const notifications = notificationStore.get(userId) || [];
  return notifications.slice(-limit).reverse();
}

/**
 * Mark notification as read
 */
export async function markNotificationAsRead(notificationId: string, userId: string): Promise<boolean> {
  const notifications = notificationStore.get(userId);
  if (!notifications) return false;

  const notification = notifications.find((n) => n.id === notificationId);
  if (notification) {
    notification.read = true;
    return true;
  }

  return false;
}

/**
 * Get unread notification count
 */
export async function getUnreadNotificationCount(userId: string): Promise<number> {
  const notifications = notificationStore.get(userId) || [];
  return notifications.filter((n) => !n.read).length;
}

/**
 * Notify tier upgrade
 */
export async function notifyTierUpgrade(
  userId: string,
  previousTier: string,
  newTier: string,
  bonusAmount: number
): Promise<VIPNotification> {
  const tierNames: Record<string, string> = {
    bronze: 'Bronze',
    silver: 'Silver',
    gold: 'Gold',
    platinum: 'Platinum',
  };

  return createVIPNotification(
    userId,
    'tier_upgrade',
    `🎉 Tier Upgrade!`,
    `Congratulations! You've been promoted from ${tierNames[previousTier]} to ${tierNames[newTier]} VIP. You've earned $${bonusAmount} as a bonus!`,
    bonusAmount,
    newTier
  );
}

/**
 * Notify monthly bonus
 */
export async function notifyMonthlyBonus(userId: string, tier: string, bonusAmount: number): Promise<VIPNotification> {
  return createVIPNotification(
    userId,
    'monthly_bonus',
    '💰 Monthly VIP Bonus',
    `Your monthly VIP bonus of $${bonusAmount} has been credited to your account!`,
    bonusAmount,
    tier
  );
}

/**
 * Notify reward earned
 */
export async function notifyRewardEarned(userId: string, rewardType: string, amount: number): Promise<VIPNotification> {
  const rewardMessages: Record<string, string> = {
    referral: 'You earned a referral reward!',
    engagement: 'You earned an engagement bonus!',
    milestone: 'You reached a spending milestone!',
    daily: 'Your daily reward has been credited!',
  };

  return createVIPNotification(
    userId,
    'reward_earned',
    '🎁 Reward Earned',
    `${rewardMessages[rewardType] || 'You earned a reward!'} $${amount} has been added to your account.`,
    amount
  );
}

/**
 * Notify exclusive game access
 */
export async function notifyExclusiveGameAccess(userId: string, gameName: string): Promise<VIPNotification> {
  return createVIPNotification(
    userId,
    'exclusive_game',
    '🎮 New Exclusive Game',
    `You now have access to "${gameName}" - an exclusive game for your VIP tier!`
  );
}

/**
 * Notify milestone achievement
 */
export async function notifyMilestoneAchieved(userId: string, milestone: string, reward: number): Promise<VIPNotification> {
  return createVIPNotification(
    userId,
    'milestone',
    '🏆 Milestone Achieved',
    `You've achieved the "${milestone}" milestone! $${reward} reward has been credited.`,
    reward
  );
}

/**
 * Get VIP analytics for real-time dashboard
 */
export async function getRealtimeVIPAnalytics() {
  const database = await db();
  const allUsers = database ? await (database as any).query.users.findMany({}) : [];

  const stats = {
    totalVIPPlayers: 0,
    activeNow: 0,
    totalSpendToday: 0,
    totalRewardsDistributed: 0,
    tierUpgradesThisMonth: 0,
    notificationsToday: 0,
    topSpenders: [] as Array<{ userId: string; username: string; spend: number }>,
  };

  // Calculate statistics
  for (const user of allUsers) {
    if (user.totalSpend && user.totalSpend > 0) {
      stats.totalVIPPlayers++;
      stats.totalSpendToday += Math.random() * 1000; // Mock daily spend
    }
  }

  // Get top spenders
  const topSpenders = allUsers
    .filter((u: any) => u.totalSpend && u.totalSpend > 0)
    .sort((a: any, b: any) => (b.totalSpend || 0) - (a.totalSpend || 0))
    .slice(0, 10)
    .map((u: any) => ({
      userId: u.id,
      username: u.username,
      spend: u.totalSpend || 0,
    }));

  stats.topSpenders = topSpenders;
  stats.activeNow = Math.floor(Math.random() * stats.totalVIPPlayers * 0.3) + 10;
  stats.totalRewardsDistributed = Math.floor(Math.random() * 50000) + 10000;
  stats.tierUpgradesThisMonth = Math.floor(Math.random() * 100) + 20;
  stats.notificationsToday = notificationStore.size * 5;

  return stats;
}

/**
 * Get notification trends
 */
export async function getNotificationTrends() {
  const trends = {
    tierUpgrades: 0,
    bonusNotifications: 0,
    rewardNotifications: 0,
    gameAccessNotifications: 0,
    milestoneNotifications: 0,
  };

  for (const [, notifications] of notificationStore) {
    for (const notif of notifications) {
      switch (notif.type) {
        case 'tier_upgrade':
          trends.tierUpgrades++;
          break;
        case 'monthly_bonus':
          trends.bonusNotifications++;
          break;
        case 'reward_earned':
          trends.rewardNotifications++;
          break;
        case 'exclusive_game':
          trends.gameAccessNotifications++;
          break;
        case 'milestone':
          trends.milestoneNotifications++;
          break;
      }
    }
  }

  return trends;
}

/**
 * Get notification analytics
 */
export async function getNotificationAnalytics() {
  const analytics = {
    totalNotifications: 0,
    totalUsers: notificationStore.size,
    avgNotificationsPerUser: 0,
    readRate: 0,
    topNotificationType: 'tier_upgrade' as const,
  };

  let totalRead = 0;
  let totalNotifications = 0;

  for (const [, notifications] of notificationStore) {
    totalNotifications += notifications.length;
    totalRead += notifications.filter((n) => n.read).length;
  }

  analytics.totalNotifications = totalNotifications;
  analytics.avgNotificationsPerUser = analytics.totalUsers > 0 ? totalNotifications / analytics.totalUsers : 0;
  analytics.readRate = totalNotifications > 0 ? (totalRead / totalNotifications) * 100 : 0;

  return analytics;
}

/**
 * Send bulk VIP notification
 */
export async function sendBulkVIPNotification(
  tier: string,
  type: VIPNotification['type'],
  title: string,
  message: string
): Promise<number> {
  const database = await db();
  const allUsers = database ? await (database as any).query.users.findMany({}) : [];
  let sentCount = 0;

  for (const user of allUsers) {
    // Check if user matches tier
    const userTier = getUserTierFromSpend(user.totalSpend || 0);
    if (userTier === tier || tier === 'all') {
      await createVIPNotification(user.id, type, title, message);
      sentCount++;
    }
  }

  return sentCount;
}

/**
 * Helper to get tier from spend
 */
function getUserTierFromSpend(spend: number): string {
  if (spend >= 15000) return 'platinum';
  if (spend >= 5000) return 'gold';
  if (spend >= 1000) return 'silver';
  return 'bronze';
}

/**
 * Clear old notifications (older than 30 days)
 */
export async function clearOldNotifications(): Promise<number> {
  let clearedCount = 0;
  const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);

  for (const [userId, notifications] of notificationStore) {
    const filtered = notifications.filter((n) => n.createdAt > thirtyDaysAgo);
    clearedCount += notifications.length - filtered.length;
    notificationStore.set(userId, filtered);
  }

  return clearedCount;
}
