import { Injectable, Inject } from "@nestjs/common";
import { InjectQueue } from "@nestjs/bullmq";
import { Queue } from "bullmq";
import { Logger } from "nestjs-pino";
import type { SendEmailOptions } from "../email.service";
import { QUEUE_NAMES } from "../../queue/queue.constants";

export type EmailJobData = SendEmailOptions & { category?: string };

@Injectable()
export class EmailQueueService {
  constructor(
    @InjectQueue(QUEUE_NAMES.EMAIL) private readonly queue: Queue<EmailJobData>,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  async enqueueEmail(data: EmailJobData): Promise<void> {
    await this.queue.add("send", data, {
      removeOnComplete: 50,
      removeOnFail: 50,
      attempts: 3,
      backoff: { type: "exponential", delay: 2000 },
    });
    this.logger.debug("Queued email", {
      to: data.to,
      subject: data.subject,
      category: data.category,
    });
  }
}
