<?php

namespace Alma\Vendor\Alma\Client\Application\Endpoint;

use Alma\Vendor\Alma\Client\Application\Request;
use Alma\Vendor\Psr\Http\Client\ClientInterface;
use Alma\Vendor\Psr\Log\LoggerAwareInterface;
use Alma\Vendor\Psr\Log\LoggerAwareTrait;
use Alma\Vendor\Psr\Log\NullLogger;

abstract class AbstractEndpoint implements LoggerAwareInterface
{
    use loggerAwareTrait;

    /** @var ClientInterface */
    protected ClientInterface $client;

    /**
     * Init the Endpoint
     * @param ClientInterface $client The Client to use with the Endpoint
     */
    public function __construct(ClientInterface $client)
    {
        $this->client = $client;
        $this->logger = new NullLogger();
    }

    /**
     * Create a Request
     * @param string $method The HTTP verb of the Request
     * @param string $uri The endpoint URI
     * @param array $body The body of the Request
     * @return Request The Request object
     */
    private function createRequest(string $method, string $uri, array $body = []): Request {

        $headers = [
            'User-Agent' => [$this->client->getConfig()->getUserAgentString()],
            'Authorization' => ['Alma-Auth ' . $this->client->getConfig()->getApiKey()]
        ];
        return new Request($method, $uri, $headers, json_encode($body));
    }

    /**
     * Create a GET Request
     *
     * @param string $uri The endpoint URI
     * @param array $queryParams The query parameters
     * @return Request The Request object
     */
    public function createGetRequest(string $uri, array $queryParams = []): Request {
        $queryString = http_build_query($queryParams);
        if ($queryString) {
            $uri .= '?' . $queryString;
        }
        return $this->createRequest('GET', $uri);
    }

    /**
     * Create a POST Request
     *
     * @param string $uri The endpoint URI
     * @param array $body The body attributes
     * @return Request The Request object
     */
    public function createPostRequest(string $uri, array $body = []): Request {
        return $this->createRequest('POST', $uri, $body);
    }

    /**
     * Create a PUT Request
     *
     * @param string $uri The endpoint URI
     * @param array $body The body attributes
     * @return Request The Request object
     */
    public function createPutRequest(string $uri, array $body = []): Request {
        return $this->createRequest('PUT', $uri, $body);
    }

    /**
     * Create de DELETE Request
     *
     * @param string $uri The endpoint URI
     * @return Request The Request object
     */
    public function createDeleteRequest(string $uri): Request {
        return $this->createRequest('DELETE', $uri);
    }
}
