/**
 * Telegram Notification Test Script
 *
 * This script tests the Telegram notification module to ensure
 * all components are working correctly.
 *
 * Run with: npx tsx src/scripts/test-telegram.ts
 */

import { notificationService } from '../modules/notification/notification.service';
import { getTelegramClient } from '../modules/notification/telegram/telegram.client';
import { logger } from '../shared/utils/logger';

/**
 * Test Telegram Client Connection
 */
async function testTelegramClient(): Promise<boolean> {
  try {
    logger.info('Testing Telegram client connection...');

    const client = getTelegramClient();
    const healthCheck = await client.healthCheck();

    if (healthCheck.healthy) {
      logger.info({
        botInfo: healthCheck.botInfo,
      }, 'Telegram client connection successful');
      return true;
    } else {
      logger.error({
        error: healthCheck.error,
      }, 'Telegram client connection failed');
      return false;
    }
  } catch (error) {
    logger.error({ error }, 'Error testing Telegram client');
    return false;
  }
}

/**
 * Test System Notification
 */
async function testSystemNotification(): Promise<boolean> {
  try {
    logger.info('Testing system notification...');

    const result = await notificationService.sendSystemNotification(
      'Test System Notification',
      'This is a test system notification from the Math Platform backend.',
      {
        test: true,
        timestamp: new Date().toISOString(),
        environment: process.env.NODE_ENV || 'development',
      }
    );

    if (result.success) {
      logger.info({
        notificationId: result.notificationId,
      }, 'System notification sent successfully');
      return true;
    } else {
      logger.error({
        error: result.error,
      }, 'Failed to send system notification');
      return false;
    }
  } catch (error) {
    logger.error({ error }, 'Error testing system notification');
    return false;
  }
}

/**
 * Test User Registration Notification
 */
async function testUserRegistrationNotification(): Promise<boolean> {
  try {
    logger.info('Testing user registration notification...');

    const result = await notificationService.notifyNewUser({
      userId: 'test-user-123',
      anonymousId: 'anon-456',
      username: 'testuser',
      email: 'test@example.com',
      registeredAt: new Date().toISOString(),
      ipAddress: '192.168.1.1',
      userAgent: 'Mozilla/5.0 Test Browser',
    });

    if (result.success) {
      logger.info({
        notificationId: result.notificationId,
      }, 'User registration notification sent successfully');
      return true;
    } else {
      logger.error({
        error: result.error,
      }, 'Failed to send user registration notification');
      return false;
    }
  } catch (error) {
    logger.error({ error }, 'Error testing user registration notification');
    return false;
  }
}

/**
 * Test Error Notification
 */
async function testErrorNotification(): Promise<boolean> {
  try {
    logger.info('Testing error notification...');

    const result = await notificationService.notifySystemError({
      errorType: 'TestError',
      errorMessage: 'This is a test error notification',
      stackTrace: 'Error: Test error\n    at testFunction (test.ts:10:5)',
      path: '/api/test',
      method: 'POST',
      statusCode: 500,
      userId: 'test-user-123',
      metadata: {
        test: true,
        environment: process.env.NODE_ENV || 'development',
      },
    });

    if (result.success) {
      logger.info({
        notificationId: result.notificationId,
      }, 'Error notification sent successfully');
      return true;
    } else {
      logger.error({
        error: result.error,
      }, 'Failed to send error notification');
      return false;
    }
  } catch (error) {
    logger.error({ error }, 'Error testing error notification');
    return false;
  }
}

/**
 * Test Module Completion Notification
 */
async function testModuleCompletionNotification(): Promise<boolean> {
  try {
    logger.info('Testing module completion notification...');

    const result = await notificationService.notifyModuleCompleted({
      userId: 'test-user-123',
      anonymousId: 'anon-456',
      moduleName: 'Vectores y Espacios Vectoriales',
      moduleType: 'FUNDAMENTOS',
      finalScore: 95,
      totalPoints: 1250,
      exercisesCompleted: 45,
      timeSpentMinutes: 120,
      startedAt: new Date(Date.now() - 7200000).toISOString(),
      completedAt: new Date().toISOString(),
    });

    if (result.success) {
      logger.info({
        notificationId: result.notificationId,
      }, 'Module completion notification sent successfully');
      return true;
    } else {
      logger.error({
        error: result.error,
      }, 'Failed to send module completion notification');
      return false;
    }
  } catch (error) {
    logger.error({ error }, 'Error testing module completion notification');
    return false;
  }
}

/**
 * Test Achievement Notification
 */
async function testTop10EntryNotification(): Promise<boolean> {
  try {
    logger.info('Testing top 10 entry notification...');

    const result = await notificationService.notifyTop10Entry({
      userId: 'test-user-123',
      anonymousId: 'anon-456',
      position: 5,
      points: 2500,
      exercisesCompleted: 120,
      streak: 15,
      moduleName: 'General',
    });

    if (result.success) {
      logger.info({
        notificationId: result.notificationId,
      }, 'Top 10 entry notification sent successfully');
      return true;
    } else {
      logger.error({
        error: result.error,
      }, 'Failed to send top 10 entry notification');
      return false;
    }
  } catch (error) {
    logger.error({ error }, 'Error testing top 10 entry notification');
    return false;
  }
}

/**
 * Get Notification Statistics
 */
async function getNotificationStats(): Promise<void> {
  try {
    const stats = await notificationService.getStatistics();

    logger.info({
      stats,
    }, 'Notification statistics');
  } catch (error) {
    logger.error({ error }, 'Error getting notification statistics');
  }
}

/**
 * Run all tests
 */
async function runTests(): Promise<void> {
  logger.info('Starting Telegram notification module tests...');

  const results = {
    clientConnection: false,
    systemNotification: false,
    userRegistration: false,
    errorNotification: false,
    moduleCompletion: false,
    top10Entry: false,
  };

  // Test 1: Client Connection
  results.clientConnection = await testTelegramClient();

  if (!results.clientConnection) {
    logger.error('Telegram client connection failed. Aborting tests.');
    return;
  }

  // Wait a bit between tests to avoid rate limiting
  await sleep(2000);

  // Test 2: System Notification
  results.systemNotification = await testSystemNotification();
  await sleep(2000);

  // Test 3: User Registration Notification
  results.userRegistration = await testUserRegistrationNotification();
  await sleep(2000);

  // Test 4: Error Notification
  results.errorNotification = await testErrorNotification();
  await sleep(2000);

  // Test 5: Module Completion Notification
  results.moduleCompletion = await testModuleCompletionNotification();
  await sleep(2000);

  // Test 6: Top 10 Entry Notification
  results.top10Entry = await testTop10EntryNotification();
  await sleep(2000);

  // Get statistics
  await getNotificationStats();

  // Print results
  logger.info({
    results,
    summary: {
      total: Object.keys(results).length,
      passed: Object.values(results).filter(r => r).length,
      failed: Object.values(results).filter(r => !r).length,
    },
  }, 'Test results summary');

  logger.info('Telegram notification module tests completed.');
}

/**
 * Sleep utility
 */
function sleep(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * Main execution
 */
async function main(): Promise<void> {
  try {
    await runTests();
    process.exit(0);
  } catch (error) {
    logger.error({ error }, 'Fatal error running tests');
    process.exit(1);
  }
}

// Run if executed directly
if (require.main === module) {
  main();
}

export {
  testTelegramClient,
  testSystemNotification,
  testUserRegistrationNotification,
  testErrorNotification,
  testModuleCompletionNotification,
  testTop10EntryNotification,
  getNotificationStats,
  runTests,
};
