<?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\Entity\Recommandation;
use Myvetshop\Module\Clinique\Repository\RecommandationRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\OptionsResolver\OptionsResolver;

class MyRecoPdfControllerAdapter implements FrontControllerAdapterInterface
{
    private CrokitApiClient $crokitApiClient;

    private RecommandationRepository $recommandationRepository;

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

    public function handleRequest(\Context $context, Request $request): array
    {
        $optionResolver = new OptionsResolver();
        $optionResolver->setDefaults([
            'id_recommandation' => null,
        ]);
        $optionResolver->setAllowedTypes('id_recommandation', ['string', 'null']);
        $optionResolver->setAllowedValues('id_recommandation', function ($value) { return null === $value || \is_numeric($value); });
        $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' => $context->customer->id,
        ]);

        if (!$recommandation || !$recommandation->codeReco) {
            return [
                'template' => '',
                'parameters' => [],
                'errors' => [
                    'id_recommandation non valide',
                ],
            ];
        }

        $response = $this->crokitApiClient->getPdf($recommandation->codeReco);

        if ($response->getStatusCode() !== 200) {
            return [
                'template' => '',
                'parameters' => [],
                'errors' => [
                    'Erreur API : Code HTTP ' . $response->getStatusCode(),
                ],
            ];
        }

        \header('Content-Type: application/pdf');
        \header('Content-Disposition: inline; filename=Recommandation-' . ($recommandation->getId() ?? 0) . '.pdf;');

        $body = $response->getBody();

        if ($body) {
            while (!$body->eof()) {
                echo $body->read(8192);
            }
        }

        exit;
    }
}
