<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\EventListener;

use Ferienpass\CoreBundle\Payments\PaymentSystem;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Makes payment routes behave as if they were never registered (404) for tenants
 * that do not use the corresponding payment feature.
 *
 *  - `_requires_payments`:         the payment system is used at all (cash or
 *                                  online) — admin payment area, receipts, etc.
 *  - `_requires_payment_provider`: an online payment provider is configured —
 *                                  the "pay online" flow.
 *
 * The check runs after routing (priority < 32) but before the firewall
 * (priority > 8), so the routes appear nonexistent rather than triggering a
 * login redirect.
 */
#[AsEventListener(event: KernelEvents::REQUEST, priority: 16)]
class PaymentRoutesListener
{
    public function __construct(private readonly PaymentSystem $paymentSystem)
    {
    }

    public function __invoke(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $attributes = $event->getRequest()->attributes;

        if ($attributes->get('_requires_payments') && !$this->paymentSystem->isEnabled()) {
            throw new NotFoundHttpException();
        }

        if ($attributes->get('_requires_payment_provider') && !$this->paymentSystem->hasOnlineProvider()) {
            throw new NotFoundHttpException();
        }
    }
}
