import { NextResponse } from "next/server";
import { createTransport } from "nodemailer";

const createEmailTransporter = () => {
  if (!process.env.EMAIL_USER || !process.env.EMAIL_APP_PASSWORD) {
    throw new Error("Email configuration is missing");
  }

  return createTransport({
    host: "smtp.gmail.com",
    port: 465,
    secure: true,
    auth: {
      user: process.env.EMAIL_USER,
      pass: process.env.EMAIL_APP_PASSWORD,
    },
  });
};

const getAvailabilityStyle = (availability: string) => {
  switch (availability) {
    case "available":
      return "color: #166534; background: #f0fdf4; padding: 2px 8px; border-radius: 4px;";
    case "not_available":
      return "color: #991b1b; background: #fef2f2; padding: 2px 8px; border-radius: 4px;";
    default:
      return "color: #854d0e; background: #fefce8; padding: 2px 8px; border-radius: 4px;";
  }
};

const getAvailabilityText = (availability: string) => {
  switch (availability) {
    case "available":
      return "Will Attend";
    case "not_available":
      return "Cannot Attend";
    default:
      return "Uncertain";
  }
};

export async function POST(request: Request) {
  try {
    const { name, email, location, availability } = await request.json();

    if (!name || !email || !location || !availability) {
      return NextResponse.json(
        { error: "Missing required fields" },
        { status: 400 }
      );
    }

    const transporter = createEmailTransporter();
    await transporter.verify();

    // Email to couple
    await transporter.sendMail({
      from: `"Wedding RSVP Notification" <${process.env.EMAIL_USER}>`,
      to: process.env.COUPLE_EMAIL,
      subject: "New Wedding RSVP",
      html: `
        <h1>New RSVP Received!</h1>
        <p><strong>Name:</strong> ${name}</p>
        <p><strong>Email:</strong> ${email}</p>
        <p><strong>Location:</strong> ${location}</p>
        <p><strong>Availability:</strong> <span style="${getAvailabilityStyle(availability)}">${getAvailabilityText(availability)}</span></p>
      `,
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Error sending RSVP email:", error);
    const errorMessage =
      error instanceof Error ? error.message : "Unknown error";
    return NextResponse.json(
      {
        error: "Error sending RSVP email",
        details: errorMessage,
      },
      { status: 500 }
    );
  }
}
