<?php

namespace Myvetshop\Module\Clinique\Api\Crokit;

use GuzzleHttp\Client;
use GuzzleHttp\Message\ResponseInterface;
use Myvetshop\Module\Clinique\Api\Crokit\Dto\CrokitRecommandation;
use Myvetshop\Module\Clinique\Api\Crokit\Normalizer\CrokitRecommandationNormalizer;

class CrokitApiClient
{
    private Client $httpClient;

    private CrokitRecommandationNormalizer $crokitRecommandationNormalizer;

    public function __construct(
        Client $httpClient,
        CrokitRecommandationNormalizer $crokitRecommandationNormalizer
    ) {
        $this->httpClient = $httpClient;
        $this->crokitRecommandationNormalizer = $crokitRecommandationNormalizer;
    }

    public function getRecommandation(string $code): ?CrokitRecommandation
    {
        $queryString = \http_build_query([
            'secure' => 'SMV4521bou',
            'codeReco' => $code,
        ]);

        $response = $this->httpClient->get('https://www.crokit.fr/MVSreturn.php?' . $queryString);
        $body = $response->getBody();
        if (404 === $response->getStatusCode() || 200 !== $response->getStatusCode() || !$body) {
            return null;
        }

        $rawContent = \json_decode($body->getContents() ?? '[]', true);

        if (!\is_array($rawContent) || \count($rawContent) !== 1 || null === ($rawContent[0]['date'] ?? null)) {
            throw new \Exception('Erreur du serveur Crokit');
        }

        $ret = $this->crokitRecommandationNormalizer->denormalize($rawContent[0], CrokitRecommandation::class);

        $ret->codeReco = $code;

        return $ret;
    }

    public function getPdf(string $code): ResponseInterface
    {
        return $this->httpClient->get('https://www.crokit.fr/pdf/' . urlencode($code) . '.pdf');
    }
}
