const nodemailer = require('nodemailer');
const { BadRequestError } = require('./errors');

// Create a transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST || 'smtp.gmail.com',
  port: process.env.SMTP_PORT || 587,
  secure: process.env.SMTP_SECURE === 'true', // true for 465, false for other ports
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASSWORD,
  },
});

/**
 * Send an email
 * @param {Object} options - Email options
 * @param {string} options.to - Email address of the recipient
 * @param {string} options.subject - Subject of the email
 * @param {string} options.text - Plain text body
 * @param {string} [options.html] - HTML body (optional)
 * @returns {Promise<Object>} - Result of the email sending operation
 */
const sendEmail = async ({ to, subject, text, html }) => {
  try {
    if (!to || !subject || (!text && !html)) {
      throw new BadRequestError('Missing required email fields');
    }

    const mailOptions = {
      from: `"${process.env.EMAIL_FROM_NAME || 'Helthstra'}" <${process.env.EMAIL_FROM || 'noreply@helthstra.com'}>`,
      to,
      subject,
      text,
      html,
    };

    // In development, log the email instead of sending it
    if (process.env.NODE_ENV === 'development') {
      console.log('Email would be sent with options:', mailOptions);
      return { message: 'Email logged (development mode)', accepted: [to] };
    }

    // In production, send the actual email
    const info = await transporter.sendMail(mailOptions);
    return info;
  } catch (error) {
    console.error('Error sending email:', error);
    throw new Error('Failed to send email');
  }
};

/**
 * Send password reset email
 * @param {string} to - Email address of the recipient
 * @param {string} resetUrl - Password reset URL
 * @returns {Promise<Object>} - Result of the email sending operation
 */
sendEmail.sendPasswordResetEmail = async (to, resetUrl) => {
  const subject = 'Password Reset Request';
  const text = `You are receiving this email because you (or someone else) has requested a password reset.\n\n` +
    `Please click on the following link to complete the process:\n\n${resetUrl}\n\n` +
    `If you did not request this, please ignore this email and your password will remain unchanged.`;

  const html = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2>Password Reset Request</h2>
      <p>You are receiving this email because you (or someone else) has requested a password reset.</p>
      <p>Please click the button below to reset your password:</p>
      <p>
        <a href="${resetUrl}" 
           style="display: inline-block; padding: 10px 20px; background-color: #4CAF50; 
                  color: white; text-decoration: none; border-radius: 4px;">
          Reset Password
        </a>
      </p>
      <p>Or copy and paste this link into your browser:</p>
      <p><a href="${resetUrl}">${resetUrl}</a></p>
      <p>If you did not request this, please ignore this email and your password will remain unchanged.</p>
      <hr>
      <p style="color: #666; font-size: 0.9em;">
        This is an automated message, please do not reply to this email.
      </p>
    </div>
  `;

  return sendEmail({ to, subject, text, html });
};

module.exports = sendEmail;
