<?php

namespace App\Http\Middleware;

use App\Services\RecaptchaService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class VerifyRecaptcha
{
    protected $recaptchaService;

    public function __construct(RecaptchaService $recaptchaService)
    {
        $this->recaptchaService = $recaptchaService;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, string $version = 'v2', string $action = null): Response
    {
        // Si reCAPTCHA n'est pas activé, passer la requête
        if (!$this->recaptchaService->isEnabled()) {
            \Illuminate\Support\Facades\Log::warning('reCAPTCHA non configuré - middleware bypassé');
            return $next($request);
        }

        $token = $request->input('g-recaptcha-response');

        if (!$token) {
            return back()
                ->withErrors(['recaptcha' => 'Veuillez vérifier que vous n\'êtes pas un robot.'])
                ->withInput();
        }

        if ($version === 'v3') {
            // Pour reCAPTCHA v3
            $result = $this->recaptchaService->verify($token, $action, 0.5);

            if (!$result['success']) {
                \Illuminate\Support\Facades\Log::warning('Échec vérification reCAPTCHA v3', [
                    'ip' => $request->ip(),
                    'score' => $result['score'] ?? 0,
                    'action' => $action,
                    'errors' => $result['errors'] ?? []
                ]);

                return back()
                    ->withErrors(['recaptcha' => 'Échec de vérification reCAPTCHA. Score trop faible.'])
                    ->withInput();
            }

            // Log success
            \Illuminate\Support\Facades\Log::info('reCAPTCHA v3 validé', [
                'ip' => $request->ip(),
                'score' => $result['score'],
                'action' => $result['action']
            ]);

        } else {
            // Pour reCAPTCHA v2
            $result = $this->recaptchaService->verify($token);

            if (!$result['success']) {
                \Illuminate\Support\Facades\Log::warning('Échec vérification reCAPTCHA v2', [
                    'ip' => $request->ip(),
                    'errors' => $result['errors'] ?? []
                ]);

                return back()
                    ->withErrors(['recaptcha' => 'Échec de vérification reCAPTCHA. Veuillez réessayer.'])
                    ->withInput();
            }

            // Log success
            \Illuminate\Support\Facades\Log::info('reCAPTCHA v2 validé', [
                'ip' => $request->ip()
            ]);
        }

        return $next($request);
    }
}
