// src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Telegraf } from 'telegraf';
import * as express from 'express';
import { Logger } from '@nestjs/common';
import { TelegramErrorFilter } from './common/filters/telegram-error.filter';
import { HttpErrorFilter } from './common/filters/http-error.filter';

const logger = new Logger('Bootstrap');

async function setupWebhook(bot: Telegraf, url: string, retries = 5) {
  for (let i = 0; i < retries; i++) {
    try {
      const webhookInfo = await bot.telegram.getWebhookInfo();
      
      if (webhookInfo.url === url) {
        logger.log('Webhook already set correctly');
        return true;
      }
      
      logger.log('Setting new webhook...');
      await bot.telegram.setWebhook(url, {
        drop_pending_updates: true,
        max_connections: 40
      });
      
      logger.log(`Webhook set successfully: ${url}`);
      return true;
    } catch (error) {
      logger.error(`Webhook attempt ${i + 1}/${retries} failed:`, error.message);
      if (i < retries - 1) {
        await new Promise(resolve => setTimeout(resolve, 5000));
      }
    }
  }
  return false;
}

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: ['error', 'warn', 'log', 'debug', 'verbose'],
  });
  
  app.use(express.json());
  app.useGlobalFilters(new HttpErrorFilter(), new TelegramErrorFilter());


  
  const bot = app.get('TELEGRAF_BOT') as Telegraf;
  
  bot.telegram.options.apiRoot = 'https://api.telegram.org';
  bot.telegram.options.agent = undefined;
  bot.telegram.options.attachmentAgent = undefined;
  
  bot.catch((err, ctx) => {
    logger.error(`Bot Error: ${err}`);
  });
  
  app.use('/webhook', express.json(), async (req, res) => {
    try {
      await bot.handleUpdate(req.body);
      res.sendStatus(200);
    } catch (error) {
      logger.error('Webhook handling error:', error.message);
      res.sendStatus(200);
    }
  });
  
  // Error handling
  process.on('uncaughtException', (error) => {
    logger.error('Uncaught Exception:', error);
  });

  process.on('unhandledRejection', (reason, promise) => {
    logger.error('Unhandled Rejection:', reason);
  });
  
  const webhookUrl = `${process.env.APP_URL}/webhook`;
  await setupWebhook(bot, webhookUrl);
  
  const port = process.env.PORT || 2001;
  await app.listen(port);
  logger.log(`🚀 Bot started on port ${port}`);
  
  process.on('SIGINT', () => bot.stop('SIGINT'));
  process.on('SIGTERM', () => bot.stop('SIGTERM'));
}

bootstrap().catch(err => {
  logger.error('Bootstrap error:', err);
});