<?php

declare(strict_types=1);

use Psr\Http\Message\ResponseInterface;

class PhpListAPI
{
    /**
     * @var string
     */
    protected $hostname;

    /**
     * @var string
     */
    protected $username;

    /**
     * @var string
     */
    protected $password;

    /**
     * @var string|null
     */
    protected $session;

    /**
     * @var \GuzzleHttp\Client
     */
    protected $client;

    /**
     * Initialisation de la session API
     *
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function initSession(): void
    {
        $response = $this->client->post(
            'http://' . $this->hostname . '/sessions', [
                'form_params' => [
                    'login_name' => $this->username,
                    'password' => $this->password,
                ],
            ]
        );

        //get session key

        $obj = json_decode(strval($response->getBody()), true);
        $this->session = $obj['key'];
    }

    /**
     * @param string $method GET/POST/PUT/DELETE
     * @param mixed|null $data
     *
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function request(string $endpoint, string $method, $data = null): ResponseInterface
    {
        if (!$this->session) {
            $this->initSession();
        }

        // TODO : A corriger
        return $this->client->request(
            $method,
            'http://' . $this->hostname . $endpoint,
            [
                'headers' => [
                    'Authorization' => 'Basic ' . base64_encode($this->username . ':' . $this->session),
                    'Content-Type' => 'application/json',
                ],
                'json' => $data,
            ]
        );
    }

    public function __construct(string $hostname, string $username, string $password)
    {
        $this->client = new \GuzzleHttp\Client();
        $this->hostname = $hostname;
        $this->username = $username;
        $this->password = $password;
    }
}
