import nodemailer from 'nodemailer';

interface EmailOptions {
  from: string;
  to: string;
  subject: string;
  html?: string;
  text?: string;
}

interface SmtpConfig {
  host: string;
  port: number;
  secure: boolean;
  auth: {
    user: string;
    pass: string;
  };
}

export async function sendEmail(options: EmailOptions, config?: SmtpConfig) {
  // Use provided config or default to environment config
  const smtpConfig = config || {
    host: process.env.SMTP_HOST || 'mail.portnimara.com',
    port: parseInt(process.env.SMTP_PORT || '465'),
    secure: process.env.SMTP_SECURE !== 'false',
    auth: {
      user: process.env.SMTP_USER || '',
      pass: process.env.SMTP_PASS || ''
    }
  };

  // Create transporter
  const transporter = nodemailer.createTransport(smtpConfig);

  // Send email
  try {
    const info = await transporter.sendMail(options);
    console.log('Email sent:', info.messageId);
    return info;
  } catch (error) {
    console.error('Failed to send email:', error);
    throw error;
  }
}
