<?php

namespace App\EventSubscriber;

use App\Entity\User;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class SubAccountPermissionSubscriber implements EventSubscriberInterface
{
    private const EVENTS_ROUTES = [
        'app_account_create_event',
        'app_account_edit_event',
        'app_account_delete_event',
        'app_account_toggle_event_online',
        'app_account_toggle_event_secret',
        'app_account_event_add_category',
        'app_account_event_edit_category',
        'app_account_event_delete_category',
        'app_account_event_reorder_categories',
        'app_account_event_add_billet',
        'app_account_event_edit_billet',
        'app_account_event_delete_billet',
        'app_account_event_reorder_billets',
        'app_account_event_billet_preview',
        'app_account_event_save_billet_design',
        'app_account_event_create_invitation',
        'app_account_event_resend_invitation',
        'app_account_event_cancel_order',
        'app_account_event_refund_order',
    ];

    private const TICKETS_ROUTES = [
        'app_account_event_add_billet',
        'app_account_event_edit_billet',
        'app_account_event_delete_billet',
        'app_account_event_reorder_billets',
        'app_account_event_billet_preview',
        'app_account_event_save_billet_design',
    ];

    public function __construct(
        private Security $security,
        private UrlGeneratorInterface $urlGenerator,
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => ['onKernelRequest', 7],
        ];
    }

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

        $user = $this->security->getUser();
        if (!$user instanceof User || !$user->getParentOrganizer()) {
            return;
        }

        $route = $event->getRequest()->attributes->getString('_route');

        if (\in_array($route, self::TICKETS_ROUTES, true) && !$user->hasPermission('tickets')) {
            $this->deny($event);

            return;
        }

        if (\in_array($route, self::EVENTS_ROUTES, true) && !$user->hasPermission('events')) {
            $this->deny($event);
        }
    }

    private function deny(RequestEvent $event): void
    {
        /** @var \Symfony\Component\HttpFoundation\Session\Session $session */
        $session = $event->getRequest()->getSession();
        $session->getFlashBag()->add('error', 'Vous n\'avez pas la permission d\'effectuer cette action.');
        $event->setResponse(new RedirectResponse($this->urlGenerator->generate('app_account')));
    }
}
