<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\EventListener;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Tracking\MarketingAttributionStorage;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

#[AsEventListener(event: KernelEvents::REQUEST, method: 'onKernelRequest', priority: 0)]
#[AsEventListener(event: KernelEvents::RESPONSE, method: 'onKernelResponse', priority: 0)]
final readonly class MarketingAttributionListener
{
    public function __construct(
        private MarketingAttributionStorage $marketingAttributionStorage,
    ) {}

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

        $request = $event->getRequest();

        if (true === $request->attributes->get('_stateless')) {
            return;
        }

        if (!\in_array($request->getMethod(), ['GET', 'HEAD'], true)) {
            return;
        }

        $route = $request->attributes->get('_route');
        if (\is_string($route) && str_starts_with($route, 'admin_')) {
            return;
        }

        $attribution = $this->marketingAttributionStorage->capture($request);

        if (null !== $attribution) {
            $request->attributes->set(MarketingAttributionStorage::REQUEST_ATTRIBUTE, $attribution);
        }
    }

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

        $request = $event->getRequest();
        if (true === $request->attributes->get('_stateless')) {
            return;
        }

        $attribution = $request->attributes->get(MarketingAttributionStorage::REQUEST_ATTRIBUTE);

        if (!\is_array($attribution)) {
            return;
        }

        $event->getResponse()->headers->setCookie(
            $this->marketingAttributionStorage->createPersistentCookie($attribution),
        );
    }
}
