import nodemailer from "nodemailer";

function confirmationTemplate(name: string) {
  return `
    <div style="font-family: Arial, sans-serif; line-height: 1.6;">
      <h2>Thanks for reaching out!</h2>
      <p>I will make my best to read your message as soon as possible!</p>
      <p>This is just a confirmation — no need to reply to this email.</p>
      <hr />
      <p style="font-size: 12px; color: #777;">
        © ${new Date().getFullYear()} 4l3ks.com
      </p>
    </div>
  `;
}
async function verifyRecaptcha(token: string) {
  const res = await fetch(
    "https://www.google.com/recaptcha/api/siteverify",
    {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: `secret=${process.env.RECAPTCHA_SECRET_KEY}&response=${token}`,
    }
  );

  return res.json();
}


export async function POST(req: Request) {
  try {
    const { name, email, subject, message, token } = await req.json();
    
    if (!process.env.RECAPTCHA_SECRET_KEY) {
      throw new Error("Missing RECAPTCHA_SECRET_KEY");
    }
    


    if (!token) {
      return Response.json(
        { success: false, error: "Missing captcha token" },
        { status: 400 }
      );
    }

    const captcha = await verifyRecaptcha(token);

    if (!captcha || captcha.success !== true) {
      console.warn("Captcha failed:", captcha);
      return Response.json(
        { success: false, error: "Captcha failed" },
        { status: 403 }
      );
    }

    // ✅ 2. ONLY NOW send emails
    const transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST!,
      port: Number(process.env.SMTP_PORT),
      secure: false,
      auth: {
        user: process.env.SMTP_USER!,
        pass: process.env.SMTP_PASS!,
      },
    });

    // Admin email
    await transporter.sendMail({
      from: `"Contact Form" <${process.env.SMTP_USER!}>`,
      to: process.env.CONTACT_EMAIL!,
      replyTo: email,
      subject: subject || `New message from ${email}`,
      html: `
        <p><strong>Name:</strong> ${name}</p>
        <p><strong>Email:</strong> ${email}</p>
        <p>${message}</p>
      `,
    });

    // Confirmation email
    await transporter.sendMail({
      from: `"4l3ks.com" <${process.env.SMTP_USER!}>`,
      to: email,
      subject: "Your message was received! :)",
      html: confirmationTemplate(name),
    });

    return Response.json({ success: true });
} catch (error) {
    console.error("CONTACT API ERROR:", error);

    return Response.json(
      {
        success: false,
        error:
          error instanceof Error
            ? error.message
            : JSON.stringify(error),
      },
      { status: 500 }
    );
  }
}
