<?php

namespace App\Http\Middleware;

use App\Facades\Settings;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Symfony\Component\HttpFoundation\Response;

class VerifyRecaptcha
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $secretKey = Settings::get('recaptcha-secret-key');

        // Skip validation if no secret key is configured (graceful degradation)
        if (empty($secretKey)) {
            return $next($request);
        }

        $token = $request->input('recaptcha_token');

        if (empty($token)) {
            return response()->json([
                'message' => 'reCAPTCHA token is required.',
                'errors' => [
                    'recaptcha_token' => ['reCAPTCHA token is required.'],
                ],
            ], 422);
        }

        $response = Http::asForm()->post('https://www.google.com/recaptcha/api/siteverify', [
            'secret' => $secretKey,
            'response' => $token,
        ]);

        $result = $response->json();
        $threshold = (float) Settings::get('recaptcha-score-threshold', 0.5);

        if (empty($result['success']) || ($result['score'] ?? 0) < $threshold) {
            return response()->json([
                'message' => 'reCAPTCHA validation failed.',
                'errors' => [
                    'recaptcha_token' => ['reCAPTCHA validation failed.'],
                ],
            ], 422);
        }

        return $next($request);
    }
}
