import { Injectable } from '@nestjs/common';
import { htmlToPlainText } from '@/modules/emails/utils/message-format';
import {
  EmailParams,
  EmailRecipient,
  EmailSender,
  SendHtmlEmailInput,
} from '@/modules/emails/services/email-sender';

@Injectable()
export class BrevoService extends EmailSender {
  private readonly apiKey: string;
  private readonly baseUrl = 'https://api.brevo.com/v3';
  private readonly senderEmail: string | undefined;
  private readonly senderName: string;

  constructor() {
    super();
    this.apiKey = process.env.BREVO_API_KEY as string;
    this.senderEmail = process.env.BREVO_SENDER_EMAIL as string | undefined;
    this.senderName = process.env.BREVO_SENDER_NAME || 'Studio M';
  }

  async sendTemplateEmail(
    to: EmailRecipient[],
    templateId: number,
    params: EmailParams,
    headers: Record<string, string> = {},
  ) {
    try {
      const body = {
        to,
        templateId,
        params,
        headers: {
          ...headers,
          charset: 'utf-8',
        },
      };

      const response = await fetch(`${this.baseUrl}/smtp/email`, {
        method: 'POST',
        headers: {
          accept: 'application/json',
          'api-key': this.apiKey,
          'content-type': 'application/json',
        },
        body: JSON.stringify(body),
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || 'Failed to send email');
      }

      return response.json();
    } catch (error) {
      console.error('Error sending email:', error);
      throw new Error('Failed to send email');
    }
  }

  async sendHtmlEmail({
    to,
    subject,
    htmlContent,
    previewText,
    headers = {},
    replyTo,
    inlineImages,
  }: SendHtmlEmailInput) {
    if (!this.senderEmail) {
      throw new Error('BREVO_SENDER_EMAIL environment variable is not defined');
    }

    try {
      const body: Record<string, unknown> = {
        sender: {
          email: this.senderEmail,
          name: this.senderName,
        },
        to,
        subject,
        headers: {
          ...headers,
          charset: 'utf-8',
        },
      };

      let finalHtmlContent = htmlContent;

      if (inlineImages && inlineImages.length > 0) {
        const inlineImagePayload: Record<string, string> = {};

        for (const image of inlineImages) {
          inlineImagePayload[image.name] = image.content;

          if (!image.dataUri) {
            continue;
          }

          const cidSource = `cid:${image.name}`;
          finalHtmlContent = finalHtmlContent
            .split(image.dataUri)
            .join(cidSource);
        }

        body.inlineImage = inlineImagePayload;
      }

      body.htmlContent = finalHtmlContent;

      const textContent = htmlToPlainText(finalHtmlContent);

      if (textContent) {
        body.textContent = textContent;
      }

      if (previewText) {
        body.previewText = previewText;
      }

      if (replyTo) {
        body.replyTo = replyTo;
      }

      const response = await fetch(`${this.baseUrl}/smtp/email`, {
        method: 'POST',
        headers: {
          accept: 'application/json',
          'api-key': this.apiKey,
          'content-type': 'application/json',
        },
        body: JSON.stringify(body),
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || 'Failed to send email');
      }

      return response.json();
    } catch (error) {
      console.error('Error sending email:', error);
      throw new Error('Failed to send email');
    }
  }
}
