/**
 * Email Mock for Testing
 *
 * Provides mock implementations for nodemailer.
 */

/**
 * Mock sent emails storage
 */
export const sentEmails: Array<{
  from: string;
  to: string;
  subject: string;
  html: string;
  timestamp: Date;
}> = [];

/**
 * Mock transporter
 */
export const mockTransporter = {
  sendMail: jest.fn().mockImplementation((mailOptions) => {
    sentEmails.push({
      from: mailOptions.from,
      to: mailOptions.to,
      subject: mailOptions.subject,
      html: mailOptions.html,
      timestamp: new Date(),
    });

    return Promise.resolve({
      messageId: `mock-message-${Date.now()}@example.com`,
      accepted: [mailOptions.to],
      rejected: [],
      response: '250 Message accepted',
    });
  }),

  verify: jest.fn().mockResolvedValue(true),
};

/**
 * Mock nodemailer
 */
export const mockNodemailer = {
  createTransport: jest.fn().mockReturnValue(mockTransporter),
};

/**
 * Reset email mocks
 */
export const resetEmailMocks = () => {
  sentEmails.length = 0;
  mockTransporter.sendMail.mockClear();
  mockTransporter.verify.mockClear();
  mockNodemailer.createTransport.mockClear();
};

/**
 * Get sent emails
 */
export const getSentEmails = () => sentEmails;

/**
 * Find email by recipient
 */
export const findEmailByRecipient = (email: string) => {
  return sentEmails.find((e) => e.to === email);
};

/**
 * Find email by subject
 */
export const findEmailBySubject = (subject: string) => {
  return sentEmails.find((e) => e.subject.includes(subject));
};

// Mock nodemailer module
jest.mock('nodemailer', () => mockNodemailer);
