import { NextResponse } from "next/server";
import { notifyAdmin } from "@/lib/email";
import { prisma } from "@/lib/prisma";
import { paymentProvider } from "@/lib/payments";
import { checkRateLimit, isHoneypotFilled } from "@/lib/rate-limit";
import { servicePaymentSchema } 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: "service-payments", windowMs: 10 * 60 * 1000, maxAttempts: 5 });
  if (!limit.allowed) return tooManyRequests(limit.retryAfterSeconds);

  const body = await request.json();
  if (body && typeof body === "object" && isHoneypotFilled((body as { companyUrl?: string }).companyUrl)) {
    return NextResponse.json({ redirect: "/payment-success" });
  }

  const parsed = servicePaymentSchema.safeParse(body);
  if (!parsed.success) return NextResponse.json({ error: "Invalid service payment" }, { status: 400 });
  const data = parsed.data;
  if (data.paymentMethod !== "STRIPE") {
    return NextResponse.json({ error: "This service fee payment method is not available yet." }, { status: 400 });
  }
  const payment = await paymentProvider(data.paymentMethod).charge({ amount: data.amount, currency: "USD", simulateFailure: data.simulateFailure });
  const servicePayment = await prisma.servicePayment.create({
    data: {
      customerName: data.customerName,
      customerEmail: data.customerEmail,
      customerPhone: data.customerPhone,
      serviceType: data.serviceType,
      amount: data.amount,
      paymentMethod: data.paymentMethod,
      paymentStatus: payment.status,
      agreementAccepted: data.agreementAccepted,
      paymentLogs: { create: { provider: payment.provider, status: payment.status, amount: data.amount, rawResponse: JSON.stringify(payment.rawResponse) } }
    }
  });
  void notifyAdmin("New service payment record", [
    `Service payment ID: ${servicePayment.id}`,
    `Customer: ${servicePayment.customerName}`,
    `Email: ${servicePayment.customerEmail}`,
    `Service type: ${servicePayment.serviceType}`,
    `Payment status: ${servicePayment.paymentStatus}`,
    "Review path: /admin/service-payments"
  ]);
  return NextResponse.json({ redirect: payment.status === "FAILED" ? "/payment-failed" : "/payment-success" });
}
