import { Controller, Post, Param, Body, HttpCode, Logger } from '@nestjs/common';
import { ApiTags, ApiExcludeEndpoint } from '@nestjs/swagger';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import { SkipThrottle } from '@nestjs/throttler';
import { TgUpdate } from '../services/telegram-api.service';
import { TgIncomingJobData } from '../processors/telegram-incoming.processor';

/**
 * Public endpoint for receiving Telegram webhook updates.
 * No auth required — Telegram sends updates here directly.
 */
@ApiTags('Telegram Bot — Webhook')
@Controller('telegram-bot/webhook')
@SkipThrottle()
export class WebhookInputController {
  private readonly logger = new Logger(WebhookInputController.name);

  constructor(
    @InjectQueue('telegram-bot-incoming')
    private readonly incomingQueue: Queue<TgIncomingJobData>,
  ) {}

  @Post(':botId')
  @HttpCode(200)
  @ApiExcludeEndpoint()
  async handleUpdate(
    @Param('botId') botId: string,
    @Body() update: TgUpdate,
  ): Promise<{ ok: true }> {
    this.logger.log(`Webhook received for bot ${botId}, update_id=${update.update_id}`);

    // Enqueue for async processing — respond 200 immediately to Telegram
    try {
      await this.incomingQueue.add(
        'process-update',
        { botId, update },
        {
          attempts: 3,
          backoff: { type: 'exponential', delay: 2000 },
          removeOnComplete: 100,
          removeOnFail: 500,
        },
      );
    } catch (err: unknown) {
      this.logger.error(
        `Failed to enqueue update: ${err instanceof Error ? err.message : String(err)}`,
      );
    }

    return { ok: true };
  }
}
