<?php

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

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

class MyRecoDeleteControllerAdapter implements FrontControllerAdapterInterface
{
    private EntityManagerInterface $entityManager;

    private RecommandationRepository $recommandationRepository;

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

    /**
     * @param \Context $context
     * @param Request $request
     *
     * @return array{template: string, parameters: array<mixed>, errors?: string[], success?: string[], redirect?: string}
     */
    public function handleRequest(
        \Context $context,
        Request $request
    ): array {
        try {
            $optionResolver = new OptionsResolver();
            $optionResolver->setDefaults([
                'id_recommandation' => null,
            ]);
            $optionResolver->setAllowedTypes('id_recommandation', ['string', 'null']);
            $optionResolver->setDefined(\array_keys($request->query->all()));

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

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

            if (!$recommandation) {
                return [
                    'template' => '',
                    'parameters' => [],
                    'errors' => [
                        'Recommandation non trouvée',
                    ],
                ];
            }

            $recommandation->deleted = true;

            $this->entityManager->flush();
        } catch (\Exception $e) {
            return [
                'template' => '',
                'parameters' => [],
                'errors' => [
                    $e->getMessage(),
                ],
            ];
        }

        return [
            'template' => '',
            'parameters' => [],
            'success' => [
                'La recommandation a bien été supprimée !',
            ],
        ];
    }
}
