import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';

export interface BotWebhookJobData {
  url: string;
  method: string;
  body: Record<string, unknown>;
  headers: Record<string, string>;
}

@Processor('telegram-bot-webhook')
export class BotWebhookProcessor extends WorkerHost {
  private readonly logger = new Logger(BotWebhookProcessor.name);

  async process(job: Job<BotWebhookJobData>): Promise<void> {
    const { url, method, body, headers } = job.data;

    this.logger.log(`Delivering bot webhook: ${method} ${url}`);

    try {
      const res = await fetch(url, {
        method: method ?? 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...headers,
        },
        body: JSON.stringify(body),
        signal: AbortSignal.timeout(10000),
      });

      if (!res.ok) {
        throw new Error(`HTTP ${res.status}: ${await res.text()}`);
      }

      this.logger.log(`Bot webhook delivered: ${url} → ${res.status}`);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : String(err);
      this.logger.warn(`Bot webhook failed: ${url} — ${msg}`);
      throw err;
    }
  }
}
