// utils/sendEmail.js
import sgMail from '@sendgrid/mail';
import dotenv from 'dotenv';

dotenv.config(); // Ensure environment variables are loaded

// Set the API Key
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const sendEmail = async ({ to, subject, text, html }) => {
  try {
    // Use the sender email from the environment variables
    const fromEmail = process.env.EMAIL_USER;
    if (!fromEmail) {
      throw new Error('Sender email (EMAIL_USER) is not defined in the environment variables.');
    }

    // Send the email using SendGrid
    await sgMail.send({
      to,
      from: fromEmail, // Your verified sender email
      subject,
      text,
      html,
    });

    console.log('Email sent successfully');
  } catch (error) {
    // Enhanced error logging for better debugging
    if (error.response) {
      console.error('Error sending email:', JSON.stringify(error.response.body, null, 2));
    } else {
      console.error('Error sending email:', error.message);
    }
    throw error; // Rethrow the error to propagate it
  }
};

export default sendEmail;