import type { APIRoute } from 'astro';
import { Resend } from 'resend';

// Initialize Resend with API key from environment variables
// IMPORTANT: Set RESEND_API_KEY in your deployment environment (e.g., Cloudflare Pages)
const resend = new Resend(import.meta.env.RESEND_API_KEY);

// Define the expected structure of the form data
interface FormData {
  name: string;
  email: string;
  subject: string;
  message: string;
}

export const POST: APIRoute = async ({ request }) => {
  // Check if API key is configured
  if (!import.meta.env.RESEND_API_KEY) {
    console.error("Resend API key is not configured.");
    return new Response(JSON.stringify({ message: 'Server configuration error.' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    });
  }

  let data: FormData;
  try {
    data = await request.json();
  } catch (error) {
    return new Response(JSON.stringify({ message: 'Invalid request body.' }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' },
    });
  }

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

  try {
    // Send email using Resend
    const { data: emailData, error: emailError } = await resend.emails.send({
      from: 'Contact Form <noreply@argobox.com>', // Replace with your desired "from" address (must be a verified domain in Resend)
      to: ['daniel.laforce@gmail.com'], // Replace with the email address where you want to receive messages
      subject: `New Contact Form Submission: ${data.subject}`,
      html: `
        <h1>New Contact Form Submission</h1>
        <p><strong>Name:</strong> ${data.name}</p>
        <p><strong>Email:</strong> ${data.email}</p>
        <p><strong>Subject:</strong> ${data.subject}</p>
        <hr>
        <p><strong>Message:</strong></p>
        <p>${data.message.replace(/\n/g, '<br>')}</p>
      `,
      reply_to: data.email, // Set the reply-to header to the sender's email
    });

    if (emailError) {
      console.error('Resend error:', emailError);
      return new Response(JSON.stringify({ message: 'Failed to send email.' }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' },
      });
    }

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

  } catch (error) {
    console.error('Unexpected error sending email:', error);
    return new Response(JSON.stringify({ message: 'An unexpected server error occurred.' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    });
  }
};