<?php
declare(strict_types=1);

namespace App\Service\Mobyt;

use App\Service\Rest\ApiRequestService;
use App\Tests\Service\Mobyt\MobytServiceTest;
use JetBrains\PhpStorm\Pure;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
 * Service d'appel à l'API Mobyt
 */
class MobytService extends ApiRequestService
{
    private string $userId;
    private string $sessionKey;

    /** @noinspection SenselessProxyMethodInspection */
    #[Pure]
    public function __construct(
        HttpClientInterface $mobyt_client
    )
    {
        parent::__construct($mobyt_client);
    }

    /**
     * Send a connexion request to mobyt and get the user id and session key from the response
     *
     * @param string $login
     * @param string $password
     * @return void
     */
    protected function connect(string $login, string $password): void
    {
        $responseContent = $this->getContent('login',[],
            [
                'headers' => [
                    'Content-Type: application/json',
                    'Authorization: Basic '. base64_encode($login.':'.$password),
                ]
            ]
        );
        [$this->userId, $this->sessionKey] = explode(';', $responseContent);
    }

    protected function getUserId(): string
    {
        return $this->userId;
    }

    protected function getSessionKey(): string
    {
        return $this->sessionKey;
    }

    /**
     * Get a mobyt user status by its opentalent organization login and password
     *
     * @param string $login
     * @param string $password
     * @return mixed[]
     * @throws \JsonException
     */
    public function getUserStatus(string $login, string $password): array
    {
        $this->connect($login, $password);
        return $this->getJsonContent(
            'status',
            ['getMoney' => 'true', 'typeAliases' => 'true'],
            [
                'headers' => [ 'user_key' => $this->getUserId(), 'Session_key' => $this->getSessionKey() ]
            ]
        );
    }

    /**
     * Test if login and pass are correct
     *
     * @param string $login
     * @param string $password
     * @return bool
     * @see MobytServiceTest::testHasCredentialsCorrect()
     */
    public function hasCredentialsCorrect(string $login, string $password): bool
    {
        try{
            $this->connect($login, $password);
        }catch (NotFoundHttpException){
            return false;
        }
        return true;
    }
}
