import type { APIRoute } from 'astro';
import nodemailer from 'nodemailer';

// Validate environment variables
const emailUser = import.meta.env.EMAIL_USER;
const emailPass = import.meta.env.EMAIL_PASS;
const emailTo = import.meta.env.EMAIL_TO || 'daniel.laforce@argobox.com'; // Default recipient

if (!emailUser || !emailPass) {
  console.error("Email credentials (EMAIL_USER, EMAIL_PASS) are not set in environment variables.");
  // Optionally, you could throw an error here during build or startup in development
}

// Configure Nodemailer transporter
// Ensure you have configured "less secure app access" in Gmail or use an App Password
// if using 2-Factor Authentication. Consider using a more robust email service
// like SendGrid, Mailgun, or Resend for production.
const transporter = nodemailer.createTransport({
    service: 'gmail', // Or your preferred service
    auth: {
        user: emailUser,
        pass: emailPass,
    },
});

export const POST: APIRoute = async ({ request }) => {
  if (!emailUser || !emailPass) {
    return new Response(JSON.stringify({ message: 'Server email configuration error.' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }

  try {
    const data = await request.json();
    const { name, email, subject, message } = data;

    // Basic validation
    if (!name || !email || !subject || !message) {
      return new Response(JSON.stringify({ message: 'Missing required fields.' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Email options
    const mailOptions = {
        from: `"${name}" <${emailUser}>`, // Display name and authorized sender
        replyTo: email, // Set reply-to for easy response
        to: emailTo, // Recipient address from env or default
        subject: `Argobox Contact Form: ${subject}`,
        text: `
Name: ${name}
Email: ${email}
Subject: ${subject}

Message:
${message}
      `,
        html: `
<h3>New Argobox Contact Form Submission</h3>
<p><strong>Name:</strong> ${name}</p>
<p><strong>Email:</strong> <a href="mailto:${email}">${email}</a></p>
<p><strong>Subject:</strong> ${subject}</p>
<h4>Message:</h4>
<p>${message.replace(/\n/g, '<br>')}</p>
      `
    };

    // Send email
    await transporter.sendMail(mailOptions);

    return new Response(JSON.stringify({ message: 'Message sent successfully!' }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (error) {
    console.error('Error processing contact form:', error);
    let errorMessage = 'Failed to send message. Please try again later.';
    if (error instanceof Error) {
        // Check for specific Nodemailer errors if needed
        // e.g., if (error.code === 'EAUTH') errorMessage = 'Server authentication error.';
    }
    return new Response(JSON.stringify({ message: errorMessage }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};

// Optional: Add a GET handler if you want to test the endpoint directly
// export const GET: APIRoute = () => {
//   return new Response(JSON.stringify({ message: 'Contact API endpoint is active. Use POST to submit.' }), {
//     status: 200,
//     headers: { 'Content-Type': 'application/json' }
//   });
// };