<?php

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

use Doctrine\ORM\EntityManagerInterface;
use Myvetshop\Module\Clinique\Adapter\Controller\FrontControllerAdapterInterface;
use Myvetshop\Module\Clinique\Entity\Animal;
use Myvetshop\Module\Clinique\Entity\Recommandation;
use Myvetshop\Module\Clinique\Repository\AnimalRepository;
use Myvetshop\Module\Clinique\Repository\RecommandationRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\OptionsResolver\OptionsResolver;

class MyRecoUpdateControllerAdapter implements FrontControllerAdapterInterface
{
    private AnimalRepository $animalRepository;

    private EntityManagerInterface $entityManager;

    private RecommandationRepository $recommandationRepository;

    public function __construct(
        AnimalRepository $animalRepository,
        EntityManagerInterface $entityManager,
        RecommandationRepository $recommandationRepository
    ) {
        $this->animalRepository = $animalRepository;
        $this->entityManager = $entityManager;
        $this->recommandationRepository = $recommandationRepository;
    }

    public function handleRequest(\Context $context, Request $request): array
    {
        $optionResolver = new OptionsResolver();
        $optionResolver->setDefaults([
            'id_animal' => null,
            'id_recommandation' => null,
        ]);
        $optionResolver->setAllowedTypes('id_animal', ['string', 'null']);
        $optionResolver->setAllowedValues('id_animal', function ($value) { return null === $value || \is_numeric($value); });
        $optionResolver->setAllowedTypes('id_recommandation', ['string', 'null']);
        $optionResolver->setAllowedValues('id_recommandation', function ($value) { return null === $value || \is_numeric($value); });
        $optionResolver->setDefined(
            \array_keys(
                \array_merge(
                    $request->query->all(),
                    $request->request->all()
                ),
            )
        );

        /** @var array{
         *     id_animal: string|null,
         *     id_recommandation: string|null,
         * } $queryParams
         */
        $queryParams = $optionResolver->resolve(
            \array_merge(
                $request->query->all(),
                $request->request->all()
            )
        );

        if (
            !$queryParams['id_recommandation']
            || !$queryParams['id_animal']
        ) {
            return [
                'template' => '',
                'parameters' => [],
                'redirect' => $context->link->getModuleLink('myvetshopclinique', 'myreco'),
                'errors' => [
                    'Un paramètre est manquant',
                ],
            ];
        }

        try {
            /** @var Recommandation|null $recommandation */
            $recommandation = $this->recommandationRepository->findOneBy([
                'id' => $queryParams['id_recommandation'],
                'idCustomer' => (int) $context->customer->id,
            ]);

            /** @var Animal|null $animal */
            $animal = $this->animalRepository->findOneBy([
                'id' => $queryParams['id_animal'],
                'idCustomer' => (int) $context->customer->id,
            ]);

            if (!$recommandation || !$animal) {
                throw new \Exception('Il n\'est pas possible de modifier cette recommandation.');
            }

            $recommandation->animal = $animal;

            $this->entityManager->flush();

            return [
                'template' => '',
                'parameters' => [],
                'success' => [
                    'La recommandation a bien été mise à jour !',
                ],
            ];
        } catch (\Exception $exception) {
            return [
                'template' => '',
                'parameters' => [],
                'errors' => [
                    $exception->getMessage(),
                ],
            ];
        }
    }
}
