<?php

declare(strict_types=1);

namespace App\EventListener;

use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Entity\Access\Access;
use App\Service\Doctrine\FiltersConfigurationService;
use App\Service\Utils\ObjectUtils;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class OnKernelRequestPreRead implements EventSubscriberInterface
{
    public function __construct(
        private RequestStack $requestStack,
        private Security $security,
        private FiltersConfigurationService $filtersConfigurationService,
    ) {
    }

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

    public function onKernelRequest(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            // don't do anything if it's not the main request
            return;
        }

        $mainRequest = $this->requestStack->getMainRequest();

        /** @var Access $access */
        $access = $this->security->getUser();
        if ($access) {
            $timeConstraintEnabled = (bool) $this->requestStack->getMainRequest()->get('_time_constraint', true);

            if ($timeConstraintEnabled) {
                // Configure les filtres pour prendre en compte les contraintes temporelles
                $this->filtersConfigurationService->configureTimeConstraintFilters($access->getId());
            }

            $profileHash = $event->getRequest()->headers->get('profileHash');
            if ($profileHash !== null) {
                $profileMask = [
                    'activityYear' => $access->getActivityYear(),
                    'historical' => $access->getHistorical(),
                ];
                $expectedHash = ObjectUtils::hash($profileMask, 'sha1');

                if ($expectedHash !== $profileHash) {
                    throw new \RuntimeException('Invalid profile hash');
                }
            }
        }
    }
}
