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,
    },
  });
};

export async function POST(request: Request) {
  try {
    const { name, email, amount, currency, message, sessionId } =
      await request.json();

    console.log(name, email, amount, currency, message, sessionId);

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

    const transporter = createEmailTransporter();

    // Verify connection configuration
    await transporter.verify();

    // Email to gifter
    await transporter.sendMail({
      from: `"Adaeze & Bolaji" <${process.env.EMAIL_USER}>`,
      to: email,
      subject: "Thank You for Your Wedding Gift",
      html: `
        <h1>Dear ${name},</h1>
        <p>Thank you so much for your generous gift of ${currency} ${amount}. Your support means the world to us as we begin our journey together.</p>
        <p>We are truly blessed to have friends like you in our lives.</p>
        <p>With love,<br>Adaeze & Bolaji</p>
      `,
    });

    // Email to couple
    await transporter.sendMail({
      from: `"Wedding Gift Notification" <${process.env.EMAIL_USER}>`,
      to: process.env.COUPLE_EMAIL,
      subject: "New Wedding Gift Received",
      html: `
        <h1>New Gift Received!</h1>
        <p><strong>From:</strong> ${name} (${email})</p>
        <p><strong>Amount:</strong> ${currency} ${amount}</p>
        ${message ? `<p><strong>Message:</strong> ${message}</p>` : ""}
        <p><strong>Stripe Session ID:</strong> ${sessionId}</p>
      `,
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Error sending emails:", error);

    // More detailed error response
    const errorMessage =
      error instanceof Error ? error.message : "Unknown error";
    return NextResponse.json(
      {
        error: "Error sending emails",
        details: errorMessage,
      },
      { status: 500 }
    );
  }
}
