<?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 StoreLocatorControllerAdapter 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([
            'latitude' => 45.9884485,
            'longitude' => -2.6998618,
            'distance' => 500,
            'start' => 0,
            'limit' => 50,
        ]);
        $optionResolver->setAllowedTypes('latitude', ['float']);
        $optionResolver->setAllowedTypes('longitude', ['float']);
        $optionResolver->setAllowedTypes('distance', ['int']);
        $optionResolver->setAllowedTypes('start', ['int']);
        $optionResolver->setAllowedTypes('limit', ['int']);
        $optionResolver->setDefined(\array_keys($request->query->all()));

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

        return ['template' => '', 'parameters' => [], 'response' => new JsonResponse(
            $this->storeRepository->findByDistance(
                $queryParams['latitude'],
                $queryParams['longitude'],
                $queryParams['distance'],
                $queryParams['start'],
                $queryParams['limit']
            )
        )];
    }
}
