<?php

declare(strict_types=1);

namespace KupShop\StorybookBundle\EventListener;

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

class StorybookResponseListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::RESPONSE => [
                ['addCorsHeaders', 100],
            ],
        ];
    }

    public function addCorsHeaders(ResponseEvent $event): void
    {
        if (!$this->isPublicGraphQLApi($event->getRequest())) {
            return;
        }

        $event->getResponse()->headers->set('Access-Control-Allow-Origin', '*');
    }

    private function isPublicGraphQLApi(Request $request): bool
    {
        return $request->getRequestUri() === '/graphql';
    }
}
