/**
 * Achievement Notification Templates
 *
 * Pre-formatted message templates for achievement-related
 * admin notifications on the Telegram backend system.
 */

import { AchievementCategory, AchievementRarity } from '@prisma/client';

/**
 * Achievement notification data
 */
export interface AchievementNotificationData {
  userId?: string;
  anonymousId: string;
  username?: string;
  achievementCode: string;
  achievementName: string;
  achievementDescription: string;
  category: AchievementCategory;
  rarity: AchievementRarity;
  pointsAwarded: number;
  icon?: string;
  progress?: number;
  requirementValue?: number;
  unlockedAt?: string;
}

/**
 * Ranking milestone notification data
 */
export interface RankingMilestoneData {
  userId?: string;
  anonymousId: string;
  username?: string;
  newPosition: number;
  previousPosition?: number;
  points: number;
  exercisesCompleted: number;
  streak?: number;
  isTop10?: boolean;
  moduleName?: string;
}

/**
 * Generate achievement unlocked notification message
 */
export function generateAchievementMessage(data: AchievementNotificationData): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);
  const rarityEmoji = getRarityEmoji(data.rarity);
  const categoryEmoji = getCategoryEmoji(data.category);

  let message = `<b>${categoryEmoji} LOGRO DESBLOQUEADO</b>\n\n`;
  message += `👤 <b>Usuario:</b> ${data.anonymousId}\n`;
  message += `${rarityEmoji} <b>Logro:</b> ${data.achievementName}\n`;
  message += `📝 <b>Descripción:</b> ${data.achievementDescription}\n`;
  message += `🏷️ <b>Categoría:</b> ${formatCategory(data.category)}\n`;
  message += `💎 <b>Rareza:</b> ${formatRarity(data.rarity)}\n`;
  message += `⭐ <b>Puntos:</b> +${data.pointsAwarded}\n`;

  if (data.progress !== undefined && data.requirementValue) {
    message += `📊 <b>Progreso:</b> ${data.progress}/${data.requirementValue}\n`;
  }

  message += `\n⏰ <i>${timestamp}</i>`;

  return message;
}

/**
 * Generate ranking milestone notification message
 */
export function generateRankingMilestoneMessage(data: RankingMilestoneData): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);
  const positionEmoji = getPositionEmoji(data.newPosition);
  const movement = data.previousPosition
    ? data.previousPosition - data.newPosition
    : 0;

  let message = `<b>🏆 HITO DE RANKING</b>\n\n`;
  message += `👤 <b>Usuario:</b> ${data.anonymousId}\n`;
  message += `${positionEmoji} <b>Nueva posición:</b> #${data.newPosition}\n`;

  if (data.previousPosition && movement !== 0) {
    const movementEmoji = movement > 0 ? '📈' : '📉';
    message += `${movementEmoji} <b>Cambio:</b> ${movement > 0 ? '+' : ''}${movement} posiciones\n`;
  }

  if (data.moduleName) {
    message += `📚 <b>Módulo:</b> ${data.moduleName}\n`;
  }

  message += `⭐ <b>Puntos:</b> ${data.points}\n`;
  message += `✅ <b>Ejercicios:</b> ${data.exercisesCompleted}\n`;

  if (data.streak && data.streak > 0) {
    message += `🔥 <b>Racha:</b> ${data.streak} días\n`;
  }

  message += `\n⏰ <i>${timestamp}</i>`;

  return message;
}

/**
 * Generate top 10 entry notification message
 */
export function generateTop10EntryMessage(data: RankingMilestoneData): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);

  let message = `<b>🎖️ TOP 10 ALCANZADO</b>\n\n`;
  message += `🏆 <b>¡El usuario entró al Top 10!</b>\n\n`;
  message += `👤 <b>Usuario:</b> ${data.anonymousId}\n`;
  message += `🥇 <b>Posición:</b> #${data.newPosition}\n`;

  if (data.moduleName) {
    message += `📚 <b>Módulo:</b> ${data.moduleName}\n`;
  } else {
    message += `🌐 <b>Ranking:</b> Global\n`;
  }

  message += `⭐ <b>Puntos totales:</b> ${data.points}\n`;
  message += `✅ <b>Ejercicios completados:</b> ${data.exercisesCompleted}\n`;

  if (data.streak && data.streak > 0) {
    message += `🔥 <b>Racha actual:</b> ${data.streak} días\n`;
  }

  message += `\n⏰ <i>${timestamp}</i>`;

  return message;
}

/**
 * Generate first achievement notification message
 */
export function generateFirstAchievementMessage(
  anonymousId: string,
  achievementName: string,
  categoryName: string
): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);

  let message = `<b>🎖️ PRIMER LOGRO</b>\n\n`;
  message += `🎉 <b>¡El usuario desbloqueó su primer logro!</b>\n\n`;
  message += `👤 <b>Usuario:</b> ${anonymousId}\n`;
  message += `🏆 <b>Logro:</b> ${achievementName}\n`;
  message += `📁 <b>Categoría:</b> ${categoryName}\n`;
  message += `\n⏰ <i>${timestamp}</i>`;

  return message;
}

/**
 * Generate rare achievement notification message
 */
export function generateRareAchievementMessage(data: AchievementNotificationData): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);

  let message = `<b>💎 LOGRO RARO DESBLOQUEADO</b>\n\n`;
  message += `👤 <b>Usuario:</b> ${data.anonymousId}\n`;
  message += `🏆 <b>Logro:</b> ${data.achievementName}\n`;
  message += `💎 <b>Rareza:</b> ${formatRarity(data.rarity)}\n`;
  message += `⭐ <b>Puntos:</b> +${data.pointsAwarded}\n`;
  message += `\n⏰ <i>${timestamp}</i>`;

  return message;
}

/**
 * Generate achievement summary for daily summary
 */
export function generateAchievementSummary(
  totalUnlockedToday: number,
  rareAchievementsUnlocked: number,
  topAchievement: { name: string; rarity: string } | null
): string {
  let message = `<b>🏆 RESUMEN DE LOGROS</b>\n\n`;
  message += `🎖️ <b>Logros desbloqueados hoy:</b> ${totalUnlockedToday}\n`;

  if (rareAchievementsUnlocked > 0) {
    message += `💎 <b>Logros raros:</b> ${rareAchievementsUnlocked}\n`;
  }

  if (topAchievement) {
    message += `🌟 <b>Logro destacado:</b> ${topAchievement.name} (${formatRarity(topAchievement.rarity as AchievementRarity)})\n`;
  }

  return message;
}

/**
 * Helper: Get rarity emoji
 */
function getRarityEmoji(rarity: AchievementRarity): string {
  const rarityEmojis: Record<AchievementRarity, string> = {
    'COMMON': '⚪',
    'RARE': '🔵',
    'EPIC': '🟣',
    'LEGENDARY': '🟡',
  };
  return rarityEmojis[rarity] || '⚪';
}

/**
 * Helper: Get category emoji
 */
function getCategoryEmoji(category: AchievementCategory): string {
  const categoryEmojis: Record<AchievementCategory, string> = {
    'EXERCISES': '✏️',
    'MODULES': '📚',
    'STREAKS': '🔥',
    'RANKING': '🏆',
    'SPECIAL': '⭐',
  };
  return categoryEmojis[category] || '🏆';
}

/**
 * Helper: Get position emoji
 */
function getPositionEmoji(position: number): string {
  if (position === 1) return '🥇';
  if (position === 2) return '🥈';
  if (position === 3) return '🥉';
  if (position <= 10) return '🎖️';
  return '📊';
}

/**
 * Helper: Format rarity
 */
function formatRarity(rarity: AchievementRarity): string {
  const rarities: Record<AchievementRarity, string> = {
    'COMMON': 'Común',
    'RARE': 'Raro',
    'EPIC': 'Épico',
    'LEGENDARY': 'Legendario',
  };
  return rarities[rarity] || rarity;
}

/**
 * Helper: Format category
 */
function formatCategory(category: AchievementCategory): string {
  const categories: Record<AchievementCategory, string> = {
    'EXERCISES': 'Ejercicios',
    'MODULES': 'Módulos',
    'STREAKS': 'Rachas',
    'RANKING': 'Ranking',
    'SPECIAL': 'Especial',
  };
  return categories[category] || category;
}

/**
 * Message type constants
 */
export const ACHIEVEMENT_MESSAGE_TYPES = {
  ACHIEVEMENT_UNLOCKED: 'ACHIEVEMENT_UNLOCKED',
  RANKING_MILESTONE: 'RANKING_MILESTONE',
  TOP_10_ENTRY: 'TOP_10_RANKING',
  FIRST_ACHIEVEMENT: 'FIRST_ACHIEVEMENT',
  RARE_ACHIEVEMENT: 'RARE_ACHIEVEMENT',
} as const;
