<?php

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

use Myvetshop\Module\Clinique\Adapter\Controller\FrontControllerAdapterInterface;
use Myvetshop\Module\Clinique\Api\Crokit\CrokitApiClient;
use Myvetshop\Module\Clinique\Presenter\RecommandationPresenter;
use Myvetshop\Module\Clinique\Repository\RecommandationRepository;
use PrestaShop\PrestaShop\Adapter\LegacyContext;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\OptionsResolver\OptionsResolver;

class MyRecoNotLoggedInControllerAdapter implements FrontControllerAdapterInterface
{
    private CrokitApiClient $crokitApiClient;

    private RecommandationPresenter $recommandationPresenter;

    private RecommandationRepository $recommandationRepository;

    private LegacyContext $legacyContext;

    public function __construct(
        CrokitApiClient $crokitApiClient,
        RecommandationPresenter $recommandationPresenter,
        RecommandationRepository $recommandationRepository,
        LegacyContext $legacyContext
    ) {
        $this->crokitApiClient = $crokitApiClient;
        $this->recommandationPresenter = $recommandationPresenter;
        $this->recommandationRepository = $recommandationRepository;
        $this->legacyContext = $legacyContext;
    }

    /**
     * @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 {
            $inputs = \array_merge(
                $request->query->all(),
                $request->request->all(),
            );

            $optionResolver = new OptionsResolver();
            $optionResolver->setDefaults([
                'code' => null,
            ]);
            $optionResolver->setAllowedTypes('code', ['string', 'null']);
            $optionResolver->setDefined(\array_keys($inputs));

            /* @var array{code: string|null} $queryParams */
            $queryParams = $optionResolver->resolve($inputs);

            $codeReco = $queryParams['code'];

            if (null === $codeReco) {
                return [
                    'template' => 'module:myvetshopclinique/views/templates/front/myreco/recommandation_public.tpl',
                    'parameters' => [
                        'code' => null,
                    ],
                ];
            }

            $recommandation = $this->crokitApiClient->getRecommandation($codeReco);

            if (null !== $recommandation) {
                $recoEnBase = $this->recommandationRepository->findOneBy(['codeReco' => $codeReco, 'deleted' => false]);

                if ($recoEnBase) {
                    return [
                        'template' => 'module:myvetshopclinique/views/templates/front/myreco/recommandation_public.tpl',
                        'parameters' => [
                            'code' => $codeReco,
                        ],
                        'errors' => [
                            'Le code fourni a déjà été importé',
                        ],
                    ];
                }
            } else {
                return [
                    'template' => 'module:myvetshopclinique/views/templates/front/myreco/recommandation_public.tpl',
                    'parameters' => [
                        'code' => $codeReco,
                    ],
                    'errors' => [
                        'Le code recommandation n\'existe pas',
                    ],
                ];
            }

            $context = $this->legacyContext->getContext();
            \assert(null !== $context);

            // Si la recommandation existe, mais que l'utilisateur n'est pas connecté, on lui demande de se connecter
            return [
                'template' => 'module:myvetshopclinique/views/templates/front/myreco/recommandation_public.tpl',
                'parameters' => [
                    'code' => $codeReco,
                    'recommandation' => $this->recommandationPresenter->presentDto($recommandation),
                    'backurl' => \rawurlencode($context->link->getModuleLink('myvetshopclinique', 'myreco', ['code' => $codeReco])),
                ],
            ];
        } catch (\Exception $e) {
            return [
                'template' => 'module:myvetshopclinique/views/templates/front/myreco/recommandation_public.tpl',
                'parameters' => [
                    'code' => null,
                ],
                'errors' => [
                    $e->getMessage(),
                ],
            ];
        }
    }
}
