import { Injectable, Inject } from "@nestjs/common";
import { Logger } from "nestjs-pino";
import { ConfigService } from "@nestjs/config";
import { SendGridEmailProvider } from "./providers/sendgrid.provider";
import { EmailQueueService, EmailJobData } from "./queue/email.queue";

export interface SendEmailOptions {
  to: string | string[];
  from?: string;
  subject: string;
  text?: string;
  html?: string;
  templateId?: string;
  dynamicTemplateData?: Record<string, unknown>;
}

@Injectable()
export class EmailService {
  constructor(
    private readonly config: ConfigService,
    private readonly provider: SendGridEmailProvider,
    private readonly queue: EmailQueueService,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  async sendEmail(options: SendEmailOptions): Promise<void> {
    const enabled = this.config.get("EMAIL_ENABLED", "true") === "true";
    if (!enabled) {
      this.logger.log("Email sending disabled; skipping", {
        to: options.to,
        subject: options.subject,
      });
      return;
    }
    const useQueue = this.config.get("EMAIL_USE_QUEUE", "true") === "true";
    if (useQueue) {
      await this.queue.enqueueEmail(options as EmailJobData);
    } else {
      await this.provider.send(options);
    }
  }
}
