import {
  buildShootingShareEmail,
  ShootingShareTemplatePayload,
} from '@/modules/emails/templates/shooting-share.template';
import {
  buildCustomerGalleryShareEmail,
  CustomerGalleryShareTemplatePayload,
} from '@/modules/emails/templates/customer-gallery-share.template';

export interface EmailRecipient {
  email: string;
  name?: string;
}

export interface EmailParams {
  [key: string]: string | number | boolean;
}

export interface InlineImage {
  name: string;
  content: string;
  dataUri?: string;
}

export interface SendHtmlEmailInput {
  to: EmailRecipient[];
  subject: string;
  htmlContent: string;
  previewText?: string;
  headers?: Record<string, string>;
  replyTo?: EmailRecipient;
  inlineImages?: InlineImage[];
}

export interface SendEmailOptions {
  replyTo?: EmailRecipient;
}

/**
 * Abstraction de l'envoi d'emails. Sert de token DI : `BrevoService` en prod,
 * `FakeEmailService` en test (cf. docs/e2e-testing-spec.md §3.1).
 *
 * Les implémentations ne fournissent que le transport (`sendTemplateEmail` /
 * `sendHtmlEmail`) ; le rendu des templates de partage reste commun.
 */
export abstract class EmailSender {
  abstract sendTemplateEmail(
    to: EmailRecipient[],
    templateId: number,
    params: EmailParams,
    headers?: Record<string, string>,
  ): Promise<unknown>;

  abstract sendHtmlEmail(input: SendHtmlEmailInput): Promise<unknown>;

  async sendShootingShareEmail(
    recipients: EmailRecipient[],
    params: {
      shootingName: string;
      shootingUrl: string;
      message?: string;
      page: 'shooting' | 'customer';
    },
  ) {
    return this.sendTemplateEmail(
      recipients,
      Number(process.env.SHARE_SHOOTING_TEMPLATE as string),
      {
        nom: params.shootingName,
        url: params.shootingUrl,
        message: params.message || '',
        page: params.page,
      },
    );
  }

  async sendShootingShareHtmlEmail(
    recipients: EmailRecipient[],
    payload: ShootingShareTemplatePayload,
    options: SendEmailOptions = {},
  ) {
    const rendered = buildShootingShareEmail(payload);

    await this.sendHtmlEmail({
      to: recipients,
      subject: rendered.subject,
      htmlContent: rendered.html,
      previewText: rendered.previewText,
      inlineImages: rendered.inlineImages,
      replyTo: options.replyTo,
    });

    return rendered;
  }

  async sendCustomerGalleryShareHtmlEmail(
    recipients: EmailRecipient[],
    payload: CustomerGalleryShareTemplatePayload,
    options: SendEmailOptions = {},
  ) {
    const rendered = buildCustomerGalleryShareEmail(payload);

    await this.sendHtmlEmail({
      to: recipients,
      subject: rendered.subject,
      htmlContent: rendered.html,
      previewText: rendered.previewText,
      inlineImages: rendered.inlineImages,
      replyTo: options.replyTo,
    });

    return rendered;
  }
}
