import { NextRequest, NextResponse } from 'next/server';
import { verifyCaptcha, clientIpFromHeaders } from '@/lib/captcha-server';

export const dynamic = 'force-dynamic';

/**
 * CAPTCHA verify-gate for forms that submit directly to the Store API from the
 * browser (newsletter, product review, registration). They POST the CAPTCHA
 * payload here first; on { valid: true } they proceed with their Store API call.
 *
 * (The contact form doesn't use this route — it already proxies through
 * /api/contact, which verifies inline before forwarding to Shopware.)
 */
export async function POST(request: NextRequest) {
  let body: Record<string, any>;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ valid: false, error: 'Invalid request.' }, { status: 400 });
  }

  const result = await verifyCaptcha(body ?? {}, clientIpFromHeaders(request.headers));
  return NextResponse.json(result, { status: result.valid ? 200 : 400 });
}
