import { createTransport, type Transporter } from 'nodemailer';

export interface SmtpConfig {
  host: string;
  port: number;
  user: string;
  pass: string;
  from: string;
}

export interface EmailTransport {
  send(to: string, subject: string, html: string): Promise<void>;
}

export function createEmailTransport(config: SmtpConfig | null): EmailTransport {
  let transporter: Transporter | null = null;

  function getTransporter(): Transporter {
    if (!transporter) {
      if (!config || !config.user || !config.pass) {
        console.warn('[EMAIL] SMTP not configured. Emails will be logged to console.');
        return {
          sendMail: async (opts: any) => {
            console.log('[EMAIL] Would send:', { to: opts.to, subject: opts.subject });
            return { messageId: 'mock' };
          },
        } as any;
      }

      transporter = createTransport({
        host: config.host,
        port: config.port,
        secure: false,
        requireTLS: true,
        auth: {
          user: config.user,
          pass: config.pass,
        },
      });
    }
    return transporter;
  }

  return {
    async send(to: string, subject: string, html: string) {
      const transport = getTransporter();
      try {
        await transport.sendMail({
          from: config?.from ?? 'noreply@example.com',
          to,
          subject,
          html,
          text: html.replace(/<[^>]*>/g, ''),
        });
      } catch (error) {
        console.error('[EMAIL] Error sending email:', error);
      }
    },
  };
}
