import { Worker, UnrecoverableError, type Job } from "bullmq";
import type { Kysely } from "kysely";
import { logError, logInfo } from "@/lib/logger";
import { ElevenLabsApiError } from "@/lib/elevenlabs/client";
import { ClickUpApiError } from "@/lib/clickup/client";
import { processGuruPostCall } from "@/internal/guru/guru-postcall.service";
import {
  GURU_POSTCALL_QUEUE,
  type GuruPostCallJobData,
} from "./guru-postcall.queue";
import { getBullMQConnection } from "./notification-target.queue";

export class GuruPostCallWorker {
  private worker: Worker<GuruPostCallJobData> | null = null;

  constructor(private readonly pool: Kysely<unknown>) {}

  start(): void {
    if (this.worker) return;

    this.worker = new Worker<GuruPostCallJobData>(
      GURU_POSTCALL_QUEUE,
      async (job: Job<GuruPostCallJobData>) => {
        const { conversationId } = job.data;
        try {
          await processGuruPostCall(this.pool, conversationId);
        } catch (err) {
          // Upstream 4xx (other than 429) won't improve with retries.
          const status =
            err instanceof ElevenLabsApiError || err instanceof ClickUpApiError
              ? err.status
              : null;
          if (status !== null && status < 500 && status !== 429) {
            throw new UnrecoverableError((err as Error).message);
          }
          throw err;
        }
      },
      { connection: getBullMQConnection(), concurrency: 2 },
    );

    this.worker.on("failed", (job, err) => {
      logError(
        `[GuruPostCallWorker] job ${job?.id} failed (attempt ${job?.attemptsMade}): ${err.message}`,
      );
    });

    logInfo("[GuruPostCallWorker] Started");
  }
}
