import sendEmail from "@lib/email";
import type { APIRoute } from "astro";

export const prerender = false;

export const POST: APIRoute = async ({ request }) => {
  const data = await request.formData();
  const email = data.get("email") as string | null;
  const subject = data.get("subject") as string | null;
  const message = data.get("message") as string | null;
  const name = data.get("name") as string | null;

  if (!email || !subject || !message || !name) {
    return new Response(
      JSON.stringify({ message: "Required field missing." }),
      {
        status: 400,
        statusText: "Missing required fields."
      }
    );
  }

  const html = `<h1>Message Received via Contact Form</h1><br>
    <b>Name</b>: ${name}<br>
    <b>Email</b>: ${email}<br>
    <b>Message</b>: ${message}`;

  try {
    await sendEmail({ email, subject, message, name, html });
  } catch (error) {
    return new Response(
      JSON.stringify({
        message: `Message failed to send with an internal server error. Please contact me directly via a method below.`
      }),
      {
        status: 500,
        statusText: `Message failed to send with an internal server error. Please contact me directly via a method below.`
      }
    );
  }

  return new Response(
    JSON.stringify({
      message:
        "Thanks for getting in touch! I will try to get back to you as soon as I can."
    }),
    {
      status: 200,
      statusText: "OK"
    }
  );
};
