<?php

declare(strict_types=1);

use GuzzleHttp\Client;

class PpsApiController
{
    public const BASE_URL_API = 'https://pps-dev.myvetshop.fr';
    public const LOGIN_TOKEN_API = 'HDdH{#bc{jID41;ugdvJOFIekdZOdbhc+f*t//M,xqJI^zhJ+:}f';

    protected Client $client;

    /**
     * PpsApiController constructor.
     */
    public function __construct()
    {
        $this->client = new GuzzleHttp\Client();
    }

    /**
     * @return array|mixed
     *
     * @throws PpsBadRequestException
     * @throws PpsNotFoundException
     * @throws PpsUnauthorizedException
     */
    public function getContractsByCustomersEmail(string $email)
    {
        $url = self::BASE_URL_API . '/api/customers/' . urlencode($email) . '/contracts';

        return $this->get($url);
    }

    /**
     * @return array|mixed
     *
     * @throws PpsBadRequestException
     * @throws PpsNotFoundException
     * @throws PpsUnauthorizedException
     */
    public function getActsByContractId($email, $idContract)
    {
        $url = self::BASE_URL_API . '/api/customers/' . $email . '/contracts/' . $idContract . '/acts';

        return $this->get($url);
    }

    /**
     * @return array|mixed
     *
     * @throws PpsBadRequestException
     * @throws PpsNotFoundException
     * @throws PpsUnauthorizedException
     */
    protected function get($url)
    {
        try {
            $res = $this->client->get(
                $url, [
                    'headers' => ['X-AUTH-TOKEN' => self::LOGIN_TOKEN_API],
                ]
            );

            return json_decode($res->getBody()->getContents(), true);
        } catch (Exception $exception) {
            if ($exception->hasResponse()) {
                $response = $exception->getResponse();
                $statusCode = $response->getStatusCode();

                if ($statusCode) {
                    switch ($statusCode) {
                        case 400:
                            throw new PpsBadRequestException();
                        case 401:
                            throw new PpsUnauthorizedException();
                        case 404:
                            throw new PpsNotFoundException();
                    }
                }
            }

            throw $exception;
        }
    }
}
