<?php declare(strict_types=1);
/*
 * This file is part of the SplendidBear Websites' projects.
 *
 * Copyright (c) 2026 @ www.splendidbear.org
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\EventListener;

use App\Service\RecaptchaService;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Http\Event\CheckPassportEvent;

/**
 * Class LoginCaptchaListener
 *
 * Validates the Google reCAPTCHA v3 token during form-login authentication.
 * Fires on CheckPassportEvent, which is dispatched after credentials are
 * collected but before the user is authenticated.
 *
 * @package  App\EventListener
 * @author   Lang <https://www.splendidbear.org>
 * @category Class
 * @license  https://www.gnu.org/licenses/lgpl-3.0.en.html GNU Lesser General Public License
 * @link     www.splendidbear.org
 * @since    2026. 04. 12.
 */
#[AsEventListener(event: CheckPassportEvent::class)]
readonly class LoginCaptchaListener
{
    public function __construct(
        private RecaptchaService $recaptcha,
        private RequestStack     $requestStack,
    ) {
    }

    public function __invoke(CheckPassportEvent $event): void
    {
        $request = $this->requestStack->getCurrentRequest();

        if ($request === null || !$request->isMethod('POST')) {
            return;
        }

        $path = $request->getPathInfo();

        if ($path === '/2fa_check' || strpos($path, '/2fa') === 0) {
            return;
        }

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

        if ($this->recaptcha->verify($token, $request->getClientIp())) {
            return;
        }

        throw new CustomUserMessageAuthenticationException('reCAPTCHA verification failed. Please try again.');
    }
}
