import { NextRequest, NextResponse } from "next/server";
import { checkRateLimit, getClientIpHeader, verifyCaptcha } from "@/lib/contact";
import { createMailerTransport, getMailerConfig } from "@/lib/mailer";

type ContactPayload = {
  name?: string;
  businessName?: string;
  email?: string;
  phone?: string;
  message?: string;
  captchaAnswer?: string;
  captchaToken?: string;
  website?: string;
};

function clean(value: unknown) {
  return typeof value === "string" ? value.trim() : "";
}

function escapeHtml(value: string) {
  return value
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#39;");
}

function isValidEmail(email: string) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

export async function POST(request: NextRequest) {
  let payload: ContactPayload;

  try {
    payload = (await request.json()) as ContactPayload;
  } catch {
    return NextResponse.json({ message: "Permintaan tidak valid." }, { status: 400 });
  }

  const name = clean(payload.name);
  const businessName = clean(payload.businessName);
  const email = clean(payload.email);
  const phone = clean(payload.phone);
  const message = clean(payload.message);
  const captchaAnswer = clean(payload.captchaAnswer);
  const captchaToken = clean(payload.captchaToken);
  const website = clean(payload.website);

  if (website) {
    return NextResponse.json({ message: "Permintaan diterima." });
  }

  const clientIp = getClientIpHeader(request.headers.get("x-forwarded-for"));
  const rateLimit = checkRateLimit(clientIp);
  if (!rateLimit.ok) {
    return NextResponse.json(
      { message: "Terlalu banyak percobaan. Coba lagi beberapa saat." },
      { status: 429 },
    );
  }

  if (!name || !businessName || !email || !phone || !message) {
    return NextResponse.json({ message: "Semua field wajib diisi." }, { status: 400 });
  }

  if (!isValidEmail(email)) {
    return NextResponse.json({ message: "Format email tidak valid." }, { status: 400 });
  }

  if (!captchaToken || !captchaAnswer) {
    return NextResponse.json({ message: "Captcha wajib diisi." }, { status: 400 });
  }

  const captcha = verifyCaptcha(captchaToken, captchaAnswer);
  if (!captcha.ok) {
    return NextResponse.json({ message: captcha.reason }, { status: 400 });
  }

  const transport = createMailerTransport();
  const mailerConfig = getMailerConfig();
  const escapedMessage = escapeHtml(message).replace(/\n/g, "<br />");

  await transport.sendMail({
    from: mailerConfig.from,
    to: mailerConfig.to,
    replyTo: email,
    subject: `Lead baru Bizone dari ${name}`,
    text: [
      "Permintaan demo baru dari website Bizone",
      "",
      `Nama: ${name}`,
      `Nama Bisnis: ${businessName}`,
      `Email: ${email}`,
      `WhatsApp: ${phone}`,
      "",
      "Kebutuhan:",
      message,
    ].join("\n"),
    html: `
      <div style="font-family:Arial,Helvetica,sans-serif;line-height:1.7;color:#10203b">
        <h2>Permintaan demo baru dari website Bizone</h2>
        <p><strong>Nama:</strong> ${escapeHtml(name)}</p>
        <p><strong>Nama Bisnis:</strong> ${escapeHtml(businessName)}</p>
        <p><strong>Email:</strong> ${escapeHtml(email)}</p>
        <p><strong>WhatsApp:</strong> ${escapeHtml(phone)}</p>
        <p><strong>Kebutuhan:</strong></p>
        <p>${escapedMessage}</p>
      </div>
    `,
  });

  return NextResponse.json({ message: "Permintaan berhasil dikirim." });
}
