const nodemailer = require('nodemailer');
const path = require('path');

// Don't load .env here - load it lazily when needed
let _envLoaded = false;
let _envPath = null;

const loadEnvIfNeeded = () => {
  if (!_envLoaded) {
    _envPath = path.join(__dirname, '../../../../.env'); // Go up 4 levels: utils -> src -> user-auth -> services -> automated-dev-pipeline
    require('dotenv').config({ path: _envPath });
    _envLoaded = true;
    console.log('📧 Environment variables loaded from:', _envPath);
  }
};

// Support env-configurable SMTP; fail if no valid configuration is provided
const createTransporter = () => {
  // Load environment variables when this function is called
  loadEnvIfNeeded();
  
  const {
    SMTP_HOST,
    SMTP_PORT,
    SMTP_SECURE,
    SMTP_USER,
    SMTP_PASS,
    SMTP_FROM,
    GMAIL_USER,
    GMAIL_APP_PASSWORD,
  } = process.env;

  console.log('🔧 Email configuration check:', {
    SMTP_HOST: SMTP_HOST ? '✓ Set' : '✗ Missing',
    SMTP_USER: SMTP_USER ? '✓ Set' : '✗ Missing',
    SMTP_PASS: SMTP_PASS ? '✓ Set' : '✗ Missing',
    GMAIL_USER: GMAIL_USER ? '✓ Set' : '✗ Missing',
    GMAIL_APP_PASSWORD: GMAIL_APP_PASSWORD ? '✓ Set' : '✗ Missing',
  });

  // Validate SMTP configuration
  if (SMTP_HOST && SMTP_USER && SMTP_PASS) {
    console.log('📧 Using SMTP configuration');
    return nodemailer.createTransport({
      host: SMTP_HOST,
      port: SMTP_PORT ? Number(SMTP_PORT) : 587,
      secure: SMTP_SECURE ? SMTP_SECURE === 'true' : false,
      auth: { user: SMTP_USER, pass: SMTP_PASS },
      socketTimeout: 300000,
      connectionTimeout: 300000,
      greetingTimeout: 300000,
    });
  }

  // Validate Gmail configuration
  if (GMAIL_USER && GMAIL_APP_PASSWORD) {
    console.log('📧 Using Gmail configuration');
    return nodemailer.createTransport({
      service: 'gmail',
      auth: {
        user: GMAIL_USER,
        pass: GMAIL_APP_PASSWORD,
      },
      socketTimeout: 300000,
      connectionTimeout: 300000,
      greetingTimeout: 300000,
    });
  }

  // Fallback to mock transporter in development mode
  if (process.env.NODE_ENV === 'development') {
    console.warn('⚠️ No email configuration found. Using mock transporter for development.');
    console.log('📧 To enable real emails, set GMAIL_USER and GMAIL_APP_PASSWORD in the .env file.');
    return {
      sendMail: async (mailOptions) => {
        console.log('📧 [MOCK] Email would be sent:', {
          to: mailOptions.to,
          subject: mailOptions.subject,
          from: mailOptions.from,
        });
        console.log('📧 [MOCK] Email content:', mailOptions.text);
        console.log('📧 [MOCK] Email HTML:', mailOptions.html);
        return {
          messageId: 'mock-' + Date.now(),
          response: 'Mock email sent successfully',
        };
      },
    };
  }

  throw new Error(
    `Email configuration is missing. Please set one of the following:

Gmail Configuration:
  GMAIL_USER=your-email@gmail.com
  GMAIL_APP_PASSWORD=your-app-password

Current environment: ${process.env.NODE_ENV || 'development'}`
  );
};

// Lazy transporter creation
let _transporter = null;

const getTransporter = () => {
  if (!_transporter) {
    try {
      _transporter = createTransporter();
      console.log('✅ Email transporter created successfully');
    } catch (err) {
      console.error('❌ Failed to create email transporter:', err.message);
      if (process.env.NODE_ENV === 'development') {
        console.log('🔄 Creating mock transporter for development...');
        _transporter = {
          sendMail: async (mailOptions) => {
            console.log('📧 [MOCK] Email would be sent:', {
              to: mailOptions.to,
              subject: mailOptions.subject,
              from: mailOptions.from,
            });
            return {
              messageId: 'mock-' + Date.now(),
              response: 'Mock email sent successfully',
            };
          },
        };
      } else {
        throw err;
      }
    }
  }
  return _transporter;
};

exports.sendMail = async (to, subject, text, html) => {
  // Load environment variables when this function is called
  loadEnvIfNeeded();
  
  console.log('🔍 sendMail called with environment variables:');
  console.log('  SMTP_FROM:', process.env.SMTP_FROM);
  console.log('  GMAIL_USER:', process.env.GMAIL_USER);
  console.log('  NODE_ENV:', process.env.NODE_ENV);

  const fromAddress = process.env.SMTP_FROM || process.env.GMAIL_USER;
  if (!fromAddress) {
    console.error('❌ No from address configured. Available env vars:', Object.keys(process.env).filter((k) => k.includes('SMTP') || k.includes('GMAIL')));
    throw new Error('No from address configured. Please set SMTP_FROM or GMAIL_USER.');
  }

  try {
    const transporter = getTransporter();
    const info = await transporter.sendMail({
      from: fromAddress,
      to,
      subject,
      text,
      html,
    });
    console.log(`✉️ Email sent to ${to}. MessageID: ${info.messageId}`);
    return info;
  } catch (err) {
    console.error('❌ Failed to send email:', {
      message: err.message,
      code: err.code,
      response: err.response,
      stack: err.stack,
    });
    throw err;
  }
};