// backend/config/email.js
const nodemailer = require('nodemailer');
const path = require('path');
const fs = require('fs');

// Busca .env en varias rutas comunes y cárgalo una sola vez
(function loadEnvOnce() {
  const candidates = [
    path.resolve(__dirname, '../.env'),     // backend/.env  ✅ (tu caso)
    path.resolve(__dirname, '../../.env'),  // proyecto/.env
    path.resolve(process.cwd(), '.env'),    // cwd/.env
  ];
  for (const p of candidates) {
    if (fs.existsSync(p)) {
      const r = require('dotenv').config({ path: p });
      console.log(`.env cargado desde: ${p}`);
      if (r.error) console.warn('⚠️ dotenv error:', r.error.message);
      break;
    }
  }
})();

function must(key) {
  const v = process.env[key];
  if (!v || !String(v).trim()) {
    throw new Error(`EMAIL_ENV_MISSING: falta configurar ${key} en .env`);
  }
  return String(v).trim();
}

// Si defines SMTP_HOST usará host/port/secure; si no, usa service:'gmail' con EMAIL_*
const useSMTP = !!process.env.SMTP_HOST;

const transporter = useSMTP
  ? nodemailer.createTransport({
      host: must('SMTP_HOST'),
      port: Number(must('SMTP_PORT')),
      secure: String(process.env.SMTP_SECURE || '').toLowerCase() === 'true' || Number(process.env.SMTP_PORT) === 465,
      auth: { user: must('SMTP_USER'), pass: must('SMTP_PASS') },
    })
  : nodemailer.createTransport({
      service: 'gmail',
      auth: { user: must('EMAIL_USER'), pass: must('EMAIL_PASS') },
    });

module.exports = transporter;
