import { Injectable, Inject } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Logger } from "nestjs-pino";
import sgMail, { MailDataRequired } from "@sendgrid/mail";

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

@Injectable()
export class SendGridEmailProvider {
  constructor(
    private readonly config: ConfigService,
    @Inject(Logger) private readonly logger: Logger
  ) {
    const apiKey = this.config.get<string>("SENDGRID_API_KEY");
    if (apiKey) {
      sgMail.setApiKey(apiKey);
    }
  }

  async send(options: ProviderSendOptions): Promise<void> {
    const from = options.from || this.config.get<string>("EMAIL_FROM");
    if (!from) {
      this.logger.warn("EMAIL_FROM is not configured; email not sent");
      return;
    }

    const message: MailDataRequired = {
      to: options.to,
      from,
      subject: options.subject,
      text: options.text,
      html: options.html,
      templateId: options.templateId,
      dynamicTemplateData: options.dynamicTemplateData,
    } as MailDataRequired;

    try {
      await sgMail.send(message);
    } catch (error) {
      this.logger.error("Failed to send email via SendGrid", {
        error: error instanceof Error ? error.message : String(error),
      });
      throw error;
    }
  }
}
