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

export interface SentTemplateEmail {
  type: 'template';
  to: EmailRecipient[];
  templateId: number;
  params: EmailParams;
  headers: Record<string, string>;
  sentAt: string;
}

export interface SentHtmlEmail {
  type: 'html';
  to: EmailRecipient[];
  subject: string;
  htmlContent: string;
  previewText?: string;
  replyTo?: EmailRecipient;
  headers: Record<string, string>;
  sentAt: string;
}

export type SentEmail = SentTemplateEmail | SentHtmlEmail;

/**
 * Implémentation de test de `EmailSender` : n'effectue aucun appel réseau et
 * conserve les emails « envoyés » en mémoire (cf. docs/e2e-testing-spec.md §3.1).
 */
@Injectable()
export class FakeEmailService extends EmailSender {
  private readonly emails: SentEmail[] = [];

  async sendTemplateEmail(
    to: EmailRecipient[],
    templateId: number,
    params: EmailParams,
    headers: Record<string, string> = {},
  ) {
    const email: SentTemplateEmail = {
      type: 'template',
      to,
      templateId,
      params,
      headers,
      sentAt: new Date().toISOString(),
    };

    this.emails.push(email);

    return email;
  }

  async sendHtmlEmail({
    to,
    subject,
    htmlContent,
    previewText,
    headers = {},
    replyTo,
  }: SendHtmlEmailInput) {
    const email: SentHtmlEmail = {
      type: 'html',
      to,
      subject,
      htmlContent,
      previewText,
      replyTo,
      headers,
      sentAt: new Date().toISOString(),
    };

    this.emails.push(email);

    return email;
  }

  getSentEmails(): SentEmail[] {
    return [...this.emails];
  }

  clear() {
    this.emails.length = 0;
  }
}
