<?php

namespace Myvetshop\Module\Clinique\Adapter\Controller\Front\Registration\Store;

use Myvetshop\Module\Clinique\Adapter\Controller\FrontControllerAdapterInterface;
use Myvetshop\Module\Clinique\Adapter\Repository\StoreRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\OptionsResolver\OptionsResolver;

class StoreSearcherControllerAdapter implements FrontControllerAdapterInterface
{
    private StoreRepository $storeRepository;

    public function __construct(
        StoreRepository $storeRepository
    ) {
        $this->storeRepository = $storeRepository;
    }

    public function handleRequest(\Context $context, Request $request): array
    {
        $optionResolver = new OptionsResolver();
        $optionResolver->setDefaults([
            'search' => null,
            'start' => 0,
            'limit' => 50,
        ]);
        $optionResolver->setAllowedTypes('search', ['string', 'null']);
        $optionResolver->setAllowedTypes('start', ['int']);
        $optionResolver->setAllowedTypes('limit', ['int']);
        $optionResolver->setDefined(\array_keys($request->query->all()));

        /* @var array{search: string, start: int, limit: int} $queryParams */
        $queryParams = $optionResolver->resolve($request->query->all());

        $results = null !== $queryParams['search']
            ? $this->storeRepository->search($queryParams['search'], $queryParams['start'], $queryParams['limit'])
            : $this->storeRepository->findAll($queryParams['start'], $queryParams['limit']);

        return ['template' => '', 'parameters' => [], 'response' => new JsonResponse($results)];
    }
}
