<?php

namespace KupShop\ComponentsBundle\Twig\DataProvider;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;
use Symfony\Contracts\Service\Attribute\Required;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\TwigComponent\ComponentRendererInterface;

trait LiveComponentRenderTrait
{
    private const HTML_CONTENT_TYPE = 'application/vnd.live-component+html';

    protected ComponentRendererInterface $componentRenderer;

    #[Required]
    final public function setComponentRenderer(ComponentRendererInterface $componentRenderer): void
    {
        $this->componentRenderer = $componentRenderer;
    }

    private function createResponse(Request $request, int $httpCacheMaxAge = 0): Response
    {
        $mounted = $request->attributes->get('_mounted_component');
        $component = $mounted->getComponent();

        foreach (AsLiveComponent::preReRenderMethods($component) as $method) {
            $component->{$method->name}();
        }

        $response = new Response($this->componentRenderer->render($mounted), 200, [
            'Content-Type' => self::HTML_CONTENT_TYPE,
        ]);

        if ($httpCacheMaxAge > 0) {
            $response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true');
            $response->setPublic();
            $response->setMaxAge(0);
            $response->setSharedMaxAge($httpCacheMaxAge);
        }

        return $response;
    }
}
