/**
 * Ranking Milestone Notifications
 * Notify players of ranking achievements and milestones
 */

import { notifyOwner } from './_core/notification.ts';

export interface RankingMilestone {
  type: 'top_10' | 'top_50' | 'top_100' | 'rank_up' | 'personal_best' | 'event_entry' | 'event_win';
  userId: string;
  gameId?: string;
  eventId?: string;
  currentRank?: number;
  previousRank?: number;
  newScore?: number;
  previousScore?: number;
  timestamp: Date;
}

export class RankingNotifications {
  /**
   * Check and send ranking milestone notifications
   */
  static async checkAndNotifyMilestones(userId: string, gameId: string, newRank: number, previousRank: number | null, newScore: number): Promise<void> {
    const milestones: RankingMilestone[] = [];

    // Check if entered top 10
    if (newRank <= 10 && (previousRank === null || previousRank > 10)) {
      milestones.push({
        type: 'top_10',
        userId,
        gameId,
        currentRank: newRank,
        timestamp: new Date(),
      });
    }

    // Check if entered top 50
    if (newRank <= 50 && (previousRank === null || previousRank > 50)) {
      milestones.push({
        type: 'top_50',
        userId,
        gameId,
        currentRank: newRank,
        timestamp: new Date(),
      });
    }

    // Check if entered top 100
    if (newRank <= 100 && (previousRank === null || previousRank > 100)) {
      milestones.push({
        type: 'top_100',
        userId,
        gameId,
        currentRank: newRank,
        timestamp: new Date(),
      });
    }

    // Check if ranked up
    if (previousRank !== null && newRank < previousRank) {
      milestones.push({
        type: 'rank_up',
        userId,
        gameId,
        currentRank: newRank,
        previousRank,
        timestamp: new Date(),
      });
    }

    // Send notifications for each milestone
    for (const milestone of milestones) {
      await this.sendMilestoneNotification(milestone);
    }
  }

  /**
   * Send milestone notification
   */
  static async sendMilestoneNotification(milestone: RankingMilestone): Promise<void> {
    const messages: Record<string, { title: string; content: string }> = {
      top_10: {
        title: '🏆 Top 10 Achievement!',
        content: `You've entered the top 10 leaderboard! Current rank: #${milestone.currentRank}`,
      },
      top_50: {
        title: '🥈 Top 50 Achievement!',
        content: `You've entered the top 50 leaderboard! Current rank: #${milestone.currentRank}`,
      },
      top_100: {
        title: '🥉 Top 100 Achievement!',
        content: `You've entered the top 100 leaderboard! Current rank: #${milestone.currentRank}`,
      },
      rank_up: {
        title: '📈 Rank Up!',
        content: `You've climbed the leaderboard! New rank: #${milestone.currentRank} (was #${milestone.previousRank})`,
      },
      personal_best: {
        title: '🎯 Personal Best!',
        content: `New personal best score: $${milestone.newScore?.toFixed(2)}!`,
      },
      event_entry: {
        title: '🎪 Event Entered!',
        content: `You've entered a seasonal leaderboard event! Compete for prizes.`,
      },
      event_win: {
        title: '🎉 Event Win!',
        content: `Congratulations! You won a seasonal leaderboard event!`,
      },
    };

    const message = messages[milestone.type];
    if (!message) return;

    // Send in-app notification
    await notifyOwner({
      title: message.title,
      content: message.content,
    });

    // In production, also send email/SMS for major milestones
    if (['top_10', 'rank_up', 'event_win'].includes(milestone.type)) {
      // Send email notification
      console.log(`[Notification] Sending email for ${milestone.type} to user ${milestone.userId}`);
    }
  }

  /**
   * Send batch milestone notifications
   */
  static async sendBatchNotifications(milestones: RankingMilestone[]): Promise<void> {
    for (const milestone of milestones) {
      await this.sendMilestoneNotification(milestone);
    }
  }

  /**
   * Get milestone history for player
   */
  static async getMilestoneHistory(userId: string, limit: number = 50): Promise<RankingMilestone[]> {
    // In production, query milestone_history table
    return [];
  }

  /**
   * Check for personal best
   */
  static async checkPersonalBest(userId: string, gameId: string, newScore: number, previousBest: number): Promise<boolean> {
    if (newScore > previousBest) {
      await this.sendMilestoneNotification({
        type: 'personal_best',
        userId,
        gameId,
        newScore,
        previousScore: previousBest,
        timestamp: new Date(),
      });
      return true;
    }
    return false;
  }

  /**
   * Notify event entry
   */
  static async notifyEventEntry(userId: string, eventId: string): Promise<void> {
    await this.sendMilestoneNotification({
      type: 'event_entry',
      userId,
      eventId,
      timestamp: new Date(),
    });
  }

  /**
   * Notify event win
   */
  static async notifyEventWin(userId: string, eventId: string, rank: number, prize: number): Promise<void> {
    await this.sendMilestoneNotification({
      type: 'event_win',
      userId,
      eventId,
      currentRank: rank,
      timestamp: new Date(),
    });

    // Send special notification for top 3
    if (rank <= 3) {
      await notifyOwner({
        title: `🏆 Event Winner - Rank #${rank}!`,
        content: `Player ${userId} won $${prize} in the seasonal event!`,
      });
    }
  }

  /**
   * Get upcoming milestone for player
   */
  static async getNextMilestone(userId: string, gameId: string, currentRank: number): Promise<{ type: string; targetRank: number; rewardBonus: number } | null> {
    const milestones = [
      { type: 'top_100', targetRank: 100, rewardBonus: 100 },
      { type: 'top_50', targetRank: 50, rewardBonus: 250 },
      { type: 'top_10', targetRank: 10, rewardBonus: 500 },
    ];

    for (const milestone of milestones) {
      if (currentRank > milestone.targetRank) {
        return milestone;
      }
    }

    return null;
  }
}
