/**
 * Alert Notification Templates
 *
 * Pre-formatted message templates for system alerts and
 * administrative notifications on the Telegram backend.
 */

/**
 * New user registration notification data
 */
export interface NewUserAlertData {
  userId?: string;
  anonymousId: string;
  username?: string;
  email?: string;
  registeredAt: string;
  ipAddress?: string;
  userAgent?: string;
  referralSource?: string;
}

/**
 * System error notification data
 */
export interface SystemErrorAlertData {
  errorType: string;
  errorMessage: string;
  stackTrace?: string;
  path?: string;
  method?: string;
  statusCode?: number;
  userId?: string;
  anonymousId?: string;
  timestamp: string;
  metadata?: Record<string, any>;
}

/**
 * Daily summary notification data
 */
export interface DailySummaryAlertData {
  date: string;
  totalUsers: number;
  newUsers: number;
  activeUsers: number;
  modulesCompleted: number;
  exercisesCompleted: number;
  achievementsUnlocked: number;
  averageSessionTime: number;
  topPerformers: Array<{
    anonymousId: string;
    points: number;
    exercisesCompleted: number;
  }>;
  errorsCount: number;
  systemHealth: 'healthy' | 'degraded' | 'critical';
}

/**
 * Generate new user registration alert message
 */
export function generateNewUserAlert(data: NewUserAlertData): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);
  const formattedDate = new Date(data.registeredAt).toLocaleDateString('es-ES', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });

  let message = `<b>👤 NUEVO USUARIO REGISTRADO</b>\n\n`;
  message += `🆔 <b>ID Usuario:</b> ${data.anonymousId}\n`;

  if (data.username) {
    message += `👤 <b>Username:</b> ${data.username}\n`;
  }

  if (data.email) {
    message += `📧 <b>Email:</b> ${maskEmail(data.email)}\n`;
  }

  message += `📅 <b>Fecha registro:</b> ${formattedDate}\n`;

  if (data.ipAddress) {
    message += `🌐 <b>IP:</b> ${maskIP(data.ipAddress)}\n`;
  }

  if (data.referralSource) {
    message += `🔗 <b>Origen:</b> ${data.referralSource}\n`;
  }

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

  return message;
}

/**
 * Generate system error alert message
 */
export function generateSystemErrorAlert(data: SystemErrorAlertData): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);
  const severityEmoji = getSeverityEmoji(data.statusCode);

  let message = `<b>🚨 ERROR DEL SISTEMA</b>\n\n`;
  message += `${severityEmoji} <b>Tipo:</b> ${data.errorType}\n`;
  if (data.errorMessage) {
    message += `❌ <b>Mensaje:</b> <code>${escapeHtml(data.errorMessage)}</code>\n`;
  }

  if (data.statusCode) {
    message += `📊 <b>Status Code:</b> ${data.statusCode}\n`;
  }

  if (data.path) {
    message += `📍 <b>Ruta:</b> <code>${data.path}</code>\n`;
  }

  if (data.method) {
    message += `🔧 <b>Método:</b> ${data.method}\n`;
  }

  if (data.anonymousId) {
    message += `👤 <b>Usuario:</b> ${data.anonymousId}\n`;
  }

  if (data.metadata && Object.keys(data.metadata).length > 0) {
    message += `📋 <b>Metadata:</b>\n`;
    for (const [key, value] of Object.entries(data.metadata)) {
      message += `   • ${key}: ${formatMetadataValue(value)}\n`;
    }
  }

  if (data.stackTrace) {
    message += `\n📝 <b>Stack trace:</b>\n<code>${escapeHtml(data.stackTrace.substring(0, 500))}</code>`;
    if (data.stackTrace.length > 500) {
      message += `\n<i>... (truncado)</i>`;
    }
  }

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

  return message;
}

/**
 * Generate daily summary alert message
 */
export function generateDailySummaryAlert(data: DailySummaryAlertData): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);
  const healthEmoji = getHealthEmoji(data.systemHealth);
  const formattedDate = new Date(data.date).toLocaleDateString('es-ES', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });

  let message = `<b>📊 RESUMEN DIARIO</b>\n\n`;
  message += `📅 <b>Fecha:</b> ${formattedDate}\n`;
  message += `${healthEmoji} <b>Estado sistema:</b> ${formatHealthStatus(data.systemHealth)}\n\n`;

  // User statistics
  message += `<b>👥 USUARIOS</b>\n`;
  message += `📊 Total: ${data.totalUsers}\n`;
  message += `🆕 Nuevos: +${data.newUsers}\n`;
  message += `🟢 Activos: ${data.activeUsers} (${((data.activeUsers / data.totalUsers) * 100).toFixed(1)}%)\n\n`;

  // Activity statistics
  message += `<b>📈 ACTIVIDAD</b>\n`;
  message += `📚 Módulos completados: ${data.modulesCompleted}\n`;
  message += `✅ Ejercicios completados: ${data.exercisesCompleted}\n`;
  message += `🏆 Logros desbloqueados: ${data.achievementsUnlocked}\n`;
  message += `⏱️ Tiempo promedio sesión: ${formatSessionTime(data.averageSessionTime)}\n\n`;

  // Top performers
  if (data.topPerformers.length > 0) {
    message += `<b>🌟 MEJORES RENDIMIENTOS</b>\n`;
    data.topPerformers.slice(0, 5).forEach((performer, index) => {
      const medal = index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : '  ';
      message += `${medal} ${performer.anonymousId} - ${performer.points} pts (${performer.exercisesCompleted} ej)\n`;
    });
    message += '\n';
  }

  // System health
  message += `<b>🔧 SISTEMA</b>\n`;
  message += `❌ Errores: ${data.errorsCount}\n`;
  message += `💚 Salud: ${formatHealthStatus(data.systemHealth)}\n`;

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

  return message;
}

/**
 * Generate database connection alert message
 */
export function generateDatabaseAlert(
  alertType: 'connection_lost' | 'connection_restored' | 'slow_query',
  details: {
    duration?: number;
    query?: string;
    timestamp: string;
  }
): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);

  let message = `<b>🗄️ ALERTA DE BASE DE DATOS</b>\n\n`;

  if (alertType === 'connection_lost') {
    message += `🔴 <b>Conexión perdida</b>\n`;
    message += `⚠️ La aplicación ha perdido la conexión con la base de datos.\n`;
  } else if (alertType === 'connection_restored') {
    message += `🟢 <b>Conexión restaurada</b>\n`;
    message += `✅ La conexión con la base de datos ha sido restablecida.\n`;
  } else if (alertType === 'slow_query') {
    message += `⚠️ <b>Consulta lenta detectada</b>\n`;
    if (details.duration) {
      message += `⏱️ Duración: ${details.duration}ms\n`;
    }
    if (details.query) {
      message += `📝 Query: <code>${escapeHtml(details.query.substring(0, 200))}</code>\n`;
    }
  }

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

  return message;
}

/**
 * Generate high load alert message
 */
export function generateHighLoadAlert(details: {
  cpuUsage: number;
  memoryUsage: number;
  activeConnections: number;
  requestsPerSecond: number;
  timestamp: string;
}): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);

  let message = `<b>⚠️ ALTA CARGA DEL SISTEMA</b>\n\n`;
  message += `📊 <b>CPU:</b> ${details.cpuUsage.toFixed(1)}%\n`;
  message += `💾 <b>Memoria:</b> ${details.memoryUsage.toFixed(1)}%\n`;
  message += `🔗 <b>Conexiones activas:</b> ${details.activeConnections}\n`;
  message += `📨 <b>Req/s:</b> ${details.requestsPerSecond.toFixed(1)}\n`;
  message += `\n⏰ <i>${timestamp}</i>`;

  return message;
}

/**
 * Generate security alert message
 */
export function generateSecurityAlert(
  alertType: 'brute_force' | 'suspicious_activity' | 'rate_limit_exceeded',
  details: {
    ipAddress?: string;
    userId?: string;
    anonymousId?: string;
    attempts?: number;
    endpoint?: string;
    timestamp: string;
  }
): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);

  let message = `<b>🔒 ALERTA DE SEGURIDAD</b>\n\n`;

  if (alertType === 'brute_force') {
    message += `🔴 <b>Posible ataque de fuerza bruta</b>\n`;
    if (details.ipAddress) {
      message += `🌐 IP: ${maskIP(details.ipAddress)}\n`;
    }
    if (details.attempts) {
      message += `� Intentos: ${details.attempts}\n`;
    }
  } else if (alertType === 'suspicious_activity') {
    message += `⚠️ <b>Actividad sospechosa detectada</b>\n`;
    if (details.anonymousId) {
      message += `👤 Usuario: ${details.anonymousId}\n`;
    }
    if (details.endpoint) {
      message += `📍 Endpoint: ${details.endpoint}\n`;
    }
  } else if (alertType === 'rate_limit_exceeded') {
    message += `🚫 <b>Límite de tasa excedido</b>\n`;
    if (details.ipAddress) {
      message += `🌐 IP: ${maskIP(details.ipAddress)}\n`;
    }
    if (details.endpoint) {
      message += `📍 Endpoint: ${details.endpoint}\n`;
    }
  }

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

  return message;
}

/**
 * Helper: Get severity emoji based on status code
 */
function getSeverityEmoji(statusCode?: number): string {
  if (!statusCode) return '⚠️';
  if (statusCode >= 500) return '🔴';
  if (statusCode >= 400) return '🟡';
  return '🟢';
}

/**
 * Helper: Get health emoji
 */
function getHealthEmoji(health: string): string {
  const emojis: Record<string, string> = {
    'healthy': '🟢',
    'degraded': '🟡',
    'critical': '🔴',
  };
  return emojis[health] || '⚪';
}

/**
 * Helper: Format health status
 */
function formatHealthStatus(health: string): string {
  const statuses: Record<string, string> = {
    'healthy': 'Saludable',
    'degraded': 'Degradado',
    'critical': 'Crítico',
  };
  return statuses[health] || health;
}

/**
 * Helper: Mask email for privacy
 */
function maskEmail(email: string): string {
  if (!email) return 'N/A';
  const [username, domain] = email.split('@');
  if (!username || !domain) return 'N/A';
  if (username.length <= 2) {
    return `${username}@${domain}`;
  }
  return `${username.substring(0, 2)}***@${domain}`;
}

/**
 * Helper: Mask IP address for privacy
 */
function maskIP(ip: string): string {
  if (!ip) return 'N/A';
  const parts = ip.split('.');
  if (parts.length !== 4) return ip.substring(0, 6) + '***';
  return `${parts[0]}.${parts[1]}.*.*`;
}

/**
 * Helper: Escape HTML special characters
 */
function escapeHtml(text: string | undefined): string {
  if (!text) return '';
  const map: Record<string, string> = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;',
  };
  return text.replace(/[&<>"']/g, m => map[m] ?? m);
}

/**
 * Helper: Format metadata value
 */
function formatMetadataValue(value: any): string {
  if (value === null || value === undefined) return 'N/A';
  if (typeof value === 'object') return JSON.stringify(value);
  return String(value);
}

/**
 * Helper: Format session time
 */
function formatSessionTime(seconds: number): string {
  if (seconds < 60) return `${seconds}s`;
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  if (minutes < 60) {
    return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`;
  }
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
}

/**
 * Message type constants
 */
export const ALERT_MESSAGE_TYPES = {
  NEW_USER: 'NEW_USER',
  SYSTEM_ERROR: 'SYSTEM_ERROR',
  DAILY_SUMMARY: 'DAILY_SUMMARY',
  DATABASE_ALERT: 'DATABASE_ALERT',
  HIGH_LOAD: 'HIGH_LOAD',
  SECURITY_ALERT: 'SECURITY_ALERT',
} as const;
