/**
 * Telegram Configuration
 *
 * Manages Telegram Bot API configuration and connection settings
 * for backend notifications. The user-facing Telegram integration
 * is completely hidden from end users.
 */

import { logger } from '../shared/utils/logger';

/**
 * Telegram Configuration Interface
 */
export interface TelegramConfig {
  botToken: string;
  adminChatId: string;
  apiBaseUrl: string;
  timeout: number;
  maxRetries: number;
  retryDelay: number;
  parseMode: 'Markdown' | 'MarkdownV2' | 'HTML';
  disableWebPagePreview: boolean;
  disableNotification: boolean;
}

/**
 * Default Telegram Configuration
 */
const DEFAULT_TELEGRAM_CONFIG: TelegramConfig = {
  botToken: process.env.TELEGRAM_BOT_TOKEN || '',
  adminChatId: process.env.TELEGRAM_ADMIN_CHAT_ID || '',
  apiBaseUrl: process.env.TELEGRAM_API_URL || 'https://api.telegram.org',
  timeout: parseInt(process.env.TELEGRAM_TIMEOUT || '10000', 10),
  maxRetries: parseInt(process.env.TELEGRAM_MAX_RETRIES || '3', 10),
  retryDelay: parseInt(process.env.TELEGRAM_RETRY_DELAY || '1000', 10),
  parseMode: (process.env.TELEGRAM_PARSE_MODE as 'Markdown' | 'MarkdownV2' | 'HTML') || 'HTML',
  disableWebPagePreview: process.env.TELEGRAM_DISABLE_WEB_PAGE_PREVIEW === 'true',
  disableNotification: process.env.TELEGRAM_DISABLE_NOTIFICATION === 'true',
};

/**
 * Telegram Message Types
 */
export enum TelegramMessageType {
  SYSTEM = 'SYSTEM',
  USER_REGISTRATION = 'USER_REGISTRATION',
  USER_ACTIVITY = 'USER_ACTIVITY',
  EXERCISE_COMPLETION = 'EXERCISE_COMPLETION',
  MODULE_COMPLETION = 'MODULE_COMPLETION',
  ACHIEVEMENT = 'ACHIEVEMENT',
  ERROR = 'ERROR',
  SECURITY = 'SECURITY',
  PERFORMANCE = 'PERFORMANCE',
}

/**
 * Telegram Priority Levels
 */
export enum TelegramPriority {
  LOW = 'LOW',
  NORMAL = 'NORMAL',
  HIGH = 'HIGH',
  URGENT = 'URGENT',
}

/**
 * Telegram Message Metadata
 */
export interface TelegramMessageMetadata {
  type: TelegramMessageType;
  priority: TelegramPriority;
  category?: string;
  userId?: string;
  sessionId?: string;
  timestamp: Date;
  correlationId?: string;
}

/**
 * Telegram Configuration Manager Singleton
 */
class TelegramConfigManager {
  private static instance: TelegramConfigManager;
  private config: TelegramConfig;
  private isEnabled: boolean;

  private constructor() {
    this.config = DEFAULT_TELEGRAM_CONFIG;
    this.isEnabled = process.env.TELEGRAM_ENABLED !== 'false';
    this.validateConfiguration();
  }

  /**
   * Get singleton instance
   */
  public static getInstance(): TelegramConfigManager {
    if (!TelegramConfigManager.instance) {
      TelegramConfigManager.instance = new TelegramConfigManager();
    }
    return TelegramConfigManager.instance;
  }

  /**
   * Validate configuration on initialization
   */
  private validateConfiguration(): void {
    if (!this.config.botToken || this.config.botToken === 'your-bot-token-here') {
      logger.warn('Telegram bot token is not configured properly');
      this.isEnabled = false;
    }

    if (!this.config.adminChatId || this.config.adminChatId === 'your-admin-chat-id') {
      logger.warn('Telegram admin chat ID is not configured properly');
      this.isEnabled = false;
    }

    if (this.isEnabled) {
      logger.info({
        adminChatId: this.config.adminChatId,
        parseMode: this.config.parseMode,
      }, 'Telegram configuration initialized successfully');
    }
  }

  /**
   * Get current configuration
   */
  public getConfig(): TelegramConfig {
    return { ...this.config };
  }

  /**
   * Check if Telegram notifications are enabled
   */
  public getEnabled(): boolean {
    return this.isEnabled;
  }

  /**
   * Enable or disable Telegram notifications
   */
  public setEnabled(enabled: boolean): void {
    this.isEnabled = enabled;
    logger.info({ enabled }, 'Telegram notifications status updated');
  }

  /**
   * Update configuration dynamically
   */
  public updateConfig(updates: Partial<TelegramConfig>): void {
    this.config = { ...this.config, ...updates };
    logger.info({ config: this.config }, 'Telegram configuration updated');
  }

  /**
   * Get bot token
   */
  public getBotToken(): string {
    return this.config.botToken;
  }

  /**
   * Get admin chat ID
   */
  public getAdminChatId(): string {
    return this.config.adminChatId;
  }

  /**
   * Get API base URL
   */
  public getApiBaseUrl(): string {
    return this.config.apiBaseUrl;
  }

  /**
   * Get timeout setting
   */
  public getTimeout(): number {
    return this.config.timeout;
  }

  /**
   * Get max retries
   */
  public getMaxRetries(): number {
    return this.config.maxRetries;
  }

  /**
   * Get retry delay
   */
  public getRetryDelay(): number {
    return this.config.retryDelay;
  }

  /**
   * Get API endpoint URL for a method
   */
  public getApiEndpoint(method: string): string {
    return `${this.config.apiBaseUrl}/bot${this.config.botToken}/${method}`;
  }

  /**
   * Validate chat ID format
   */
  public isValidChatId(chatId: string): boolean {
    // Chat IDs can be numeric (user/group) or @username (channels)
    const numericPattern = /^-?\d+$/;
    const usernamePattern = /^@\w{5,32}$/;
    return numericPattern.test(chatId) || usernamePattern.test(chatId);
  }

  /**
   * Check if message type should be sent based on priority
   */
  public shouldSendByPriority(priority: TelegramPriority): boolean {
    const minimumPriority = (process.env.TELEGRAM_MIN_PRIORITY as TelegramPriority) || TelegramPriority.NORMAL;

    const priorityLevels = {
      [TelegramPriority.LOW]: 0,
      [TelegramPriority.NORMAL]: 1,
      [TelegramPriority.HIGH]: 2,
      [TelegramPriority.URGENT]: 3,
    };

    return priorityLevels[priority] >= priorityLevels[minimumPriority];
  }

  /**
   * Health check for Telegram configuration
   */
  public healthCheck(): { healthy: boolean; config: Partial<TelegramConfig> } {
    return {
      healthy: this.isEnabled &&
        !!this.config.botToken &&
        !!this.config.adminChatId &&
        this.isValidChatId(this.config.adminChatId),
      config: {
        adminChatId: this.config.adminChatId,
        parseMode: this.config.parseMode,
        timeout: this.config.timeout,
        maxRetries: this.config.maxRetries,
      },
    };
  }
}

/**
 * Export singleton instance
 */
export const telegramConfig = TelegramConfigManager.getInstance();

/**
 * Export convenience functions
 */
export function getTelegramConfig(): TelegramConfig {
  return telegramConfig.getConfig();
}

export function isTelegramEnabled(): boolean {
  return telegramConfig.getEnabled();
}

export function getTelegramBotToken(): string {
  return telegramConfig.getBotToken();
}

export function getTelegramAdminChatId(): string {
  return telegramConfig.getAdminChatId();
}

export function getTelegramApiEndpoint(method: string): string {
  return telegramConfig.getApiEndpoint(method);
}

export function shouldSendByPriority(priority: TelegramPriority): boolean {
  return telegramConfig.shouldSendByPriority(priority);
}

/**
 * Type guards
 */
export function isValidTelegramMessageType(type: string): type is TelegramMessageType {
  return Object.values(TelegramMessageType).includes(type as TelegramMessageType);
}

export function isValidTelegramPriority(priority: string): priority is TelegramPriority {
  return Object.values(TelegramPriority).includes(priority as TelegramPriority);
}

export default telegramConfig;
