<?php

declare(strict_types=1);

namespace KupShop\SellerBundle\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class ResponseSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::RESPONSE => [
                ['onResponseSetCookie', 200],
            ],
        ];
    }

    public function onResponseSetCookie(ResponseEvent $event): void
    {
        if (!($request = $event->getRequest())) {
            return;
        }

        // pokud neni na requestu nasetovany attribut sellerId, tak se nic nezmenilo a nemusim nic setovat
        if (!($sellerId = $request->attributes->get('sellerId'))) {
            return;
        }

        // nastavim cookie se sellerId na 1 rok
        $event->getResponse()->headers->setCookie(
            Cookie::create('sellerId', (string) $sellerId)
                ->withExpires(
                    (new \DateTime())->add(new \DateInterval('P1Y'))
                )
        );
    }
}
