import { NextResponse } from "next/server";

export async function POST(req: Request) {
  const { token, action } = await req.json();

  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}`,
  });

  const data = await res.json();

  // Invalid or tampered token
  if (!data.success) {
    return NextResponse.json(
      { success: false, reason: "verification_failed" },
      { status: 403 }
    );
  }

  // Action mismatch (extra security)
  if (action && data.action !== action) {
    return NextResponse.json(
      { success: false, reason: "action_mismatch" },
      { status: 403 }
    );
  }

  // Hard block (very likely bot)
  if (data.score < 0.5) {
    return NextResponse.json(
      { success: false, score: data.score, level: "blocked" },
      { status: 403 }
    );
  }

  // Suspicious but allowed
  if (data.score < 0.7) {
    return NextResponse.json({
      success: true,
      score: data.score,
      level: "suspicious",
    });
  }

  //  Clean human traffic
  return NextResponse.json({
    success: true,
    score: data.score,
    level: "trusted",
  });
}
