import { NextResponse } from "next/server";
import { notifyAdmin } from "@/lib/email";
import { prisma } from "@/lib/prisma";
import { checkRateLimit, isHoneypotFilled } from "@/lib/rate-limit";
import { iraTrustSchema } from "@/lib/validations";

function tooManyRequests(retryAfterSeconds: number) {
  return NextResponse.json(
    { success: false, message: "Too many requests. Please wait a few minutes and try again.", error: "Too many requests. Please wait a few minutes and try again." },
    { status: 429, headers: { "Retry-After": String(retryAfterSeconds) } }
  );
}

export async function POST(request: Request) {
  const limit = checkRateLimit(request, { route: "ira-trust", windowMs: 15 * 60 * 1000, maxAttempts: 3 });
  if (!limit.allowed) return tooManyRequests(limit.retryAfterSeconds);

  const form = await request.formData();
  if (isHoneypotFilled(form.get("companyUrl"))) {
    return NextResponse.json({ ok: true });
  }

  const data = Object.fromEntries(form.entries());
  const parsed = iraTrustSchema.safeParse({
    ...data,
    amlKycAccepted: form.get("amlKycAccepted") === "on",
    custodianAgreementAccepted: form.get("custodianAgreementAccepted") === "on",
    storageAgreementAccepted: form.get("storageAgreementAccepted") === "on",
    serviceAgreementAccepted: form.get("serviceAgreementAccepted") === "on"
  });
  if (!parsed.success) return NextResponse.json({ error: "Invalid application" }, { status: 400 });
  const application = await prisma.iraTrustApplication.create({ data: parsed.data });
  void notifyAdmin("New IRA/trust application", [
    `Application ID: ${application.id}`,
    `Requester: ${application.fullName}`,
    `Email: ${application.email}`,
    `Account type: ${application.accountType}`,
    "Review path: /admin/ira-trust-applications"
  ]);
  return NextResponse.json({ ok: true });
}
