const nodemailer = require('nodemailer');

const sendEmail = async (options) => {
  // Configuración de transporte
  // Para pruebas locales, puedes usar Ethereal Email o configurar tus propias credenciales en .env
  const transporter = nodemailer.createTransport({
    host: process.env.MAIL_HOST || process.env.SMTP_HOST || 'smtp.mailtrap.io',
    port: process.env.MAIL_PORT || process.env.SMTP_PORT || 2525,
    auth: {
      user: process.env.MAIL_USERNAME || process.env.SMTP_EMAIL,
      pass: process.env.MAIL_PASSWORD || process.env.SMTP_PASSWORD
    }
  });

  const message = {
    from: `${process.env.MAIL_FROM_NAME || process.env.FROM_NAME || 'Ganared'} <${process.env.MAIL_FROM_ADDRESS || process.env.FROM_EMAIL || 'noreply@ganared.com'}>`,
    to: options.email,
    subject: options.subject,
    text: options.message
  };

  try {
    const info = await transporter.sendMail(message);
    console.log('Message sent: %s', info.messageId);
  } catch (error) {
    console.error('Error sending email:', error);
    // Para desarrollo local si falla el envío real, mostramos el token en consola
    if (process.env.NODE_ENV !== 'production') {
      console.log('--- EMAIL MOCK ---');
      console.log('To:', options.email);
      console.log('Subject:', options.subject);
      console.log('Message:', options.message);
      console.log('------------------');
    }
    // No lanzamos error para no romper el flujo en dev si no hay SMTP configurado
  }
};

module.exports = sendEmail;
