import { NextResponse } from "next/server";
import { notifyAdmin } from "@/lib/email";
import { prisma } from "@/lib/prisma";
import { checkRateLimit, isHoneypotFilled } from "@/lib/rate-limit";
import { sellBackSchema } 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: "sell-back", 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 raw = Object.fromEntries(form.entries());
  const parsed = sellBackSchema.safeParse({
    ...raw,
    purchaseDate: raw.purchaseDate || undefined,
    ownershipDeclarationAccepted: form.get("ownershipDeclarationAccepted") === "on",
    amlKycAccepted: form.get("amlKycAccepted") === "on"
  });
  if (!parsed.success) return NextResponse.json({ error: "Invalid sell-back request" }, { status: 400 });
  const requestRecord = await prisma.sellBackRequest.create({ data: parsed.data });
  void notifyAdmin("New sell-back request", [
    `Request ID: ${requestRecord.id}`,
    `Requester: ${requestRecord.fullName}`,
    `Email: ${requestRecord.email}`,
    `Product type: ${requestRecord.productType}`,
    "Review path: /admin/sell-back-requests"
  ]);
  return NextResponse.json({ ok: true });
}
