import { Injectable, Logger } from '@nestjs/common';
import { SettingsService } from '../settings.service';
import type { TelegramUpdate } from './telegram-serializer.service';

@Injectable()
export class BotWebhookDispatcherService {
  private readonly logger = new Logger(BotWebhookDispatcherService.name);

  constructor(private readonly settings: SettingsService) {}

  async dispatch(webhookUrl: string, update: TelegramUpdate, secretToken?: string | null) {
    const timeoutMs = await this.settings.getNumber('BOT_WEBHOOK_TIMEOUT_MS', 10_000);
    const maxAttempts = await this.settings.getNumber('BOT_WEBHOOK_MAX_RETRIES', 3);

    let lastError: unknown;
    for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
      try {
        const response = await fetch(webhookUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            ...(secretToken ? { 'X-Telegram-Bot-Api-Secret-Token': secretToken } : {})
          },
          body: JSON.stringify(update),
          signal: AbortSignal.timeout(timeoutMs)
        });

        if (response.ok) {
          return;
        }

        lastError = new Error(`Webhook HTTP ${response.status}`);
      } catch (error) {
        lastError = error;
      }

      if (attempt < maxAttempts) {
        const delayMs = Math.min(1000 * 2 ** (attempt - 1), 8000);
        await new Promise((resolve) => setTimeout(resolve, delayMs));
      }
    }

    this.logger.warn(
      `Не удалось доставить update ${update.update_id} на webhook ${webhookUrl}: ${
        lastError instanceof Error ? lastError.message : lastError
      }`
    );
  }
}
