<?php

namespace App\Library\Framework\Controller;

use App\Library\Action\Handler\LibrarySearchHandler;
use App\Library\Action\Input\LibrarySearchInput;
use App\Library\Action\Result\LibrarySearchResult;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\UX\Turbo\TurboBundle;

class Api extends AbstractController
{
    #[Route('/api/library/search', name: 'api.library.search', methods: ['GET'])]
    public function search(LibrarySearchInput $input, LibrarySearchHandler $handler, Request $request): Response
    {
        $result = $handler->handle($input->toCommand());

        if ($request->headers->get('Turbo-Frame')) {
            return $this->sendFragmentResponse($result, $request);
        }

        return $this->json($handler->handle($input->toCommand()));
    }

    private function sendFragmentResponse(LibrarySearchResult $result, Request $request): Response
    {
        $request->setRequestFormat(TurboBundle::STREAM_FORMAT);
        return $this->renderBlock(
            'search/fragments.html.twig',
            $request->query->get('block'),
            [
                'result' => $result,
                'target' => $request->query->get('target')
            ]
        );
    }
}
