<?php

namespace App\EventSubscriber;

use App\Security\DeviceCookieFactory;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

#[AsEventListener(event: KernelEvents::RESPONSE)]
final class DeviceCookieRefreshSubscriber
{
    public function __construct(private readonly DeviceCookieFactory $cookies)
    {
    }

    public function __invoke(ResponseEvent $event): void
    {
        $refresh = $event->getRequest()->attributes->get('_device_cookie_refresh');

        if (!is_array($refresh) || 2 !== count($refresh) || !$refresh[1] instanceof \DateTimeImmutable) {
            return;
        }

        $event->getResponse()->headers->setCookie($this->cookies->create((string) $refresh[0], $refresh[1]));
    }
}
