<?php
namespace ElixForms;

use ElixForms\Auth\ElixFormsAuthenticationClient as AuthClient;
use ElixForms\Exceptions\ElixFormsException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class ElixFormsClient
{
    private string $baseUrl;
    private Client $httpClient;

    public function __construct(string $baseUrl, ?Client $httpClient)
    {
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->httpClient = $httpClient ?? new Client(['timeout' => 10.0, 'http_errors' => false]);
    }

    public function auth(): AuthClient
    {
        return new AuthClient($this->baseUrl, $this->httpClient);
    }

    public function request(string $method, string $path, ?array $body, array $headers = []): array
    {
        $url = $this->baseUrl . '/' . ltrim($path, '/');
        $options = ['headers' => $headers];

        if ($body !== null) {
            $options['json'] = $body;
        }

        try {
            $response = $this->httpClient->request($method, $url, $options);
            $status = $response->getStatusCode();
            $bodyRaw = $response->getBody()->getContents();
            $contentType = $response->getHeaderLine('Content-Type');
            $isJson = stripos($contentType, 'application/json') !== false;

            return [
                'status' => $status,
                'headers' => $response->getHeaders(),
                'body' => $bodyRaw,
                'is_json' => $isJson,
                'json' => $isJson ? json_decode($bodyRaw, true) : null,
            ];
        } catch (GuzzleException $e) {
            throw new ElixFormsException('Errore di connessione al server elixForms: ' . $e->getMessage(), 0, $e);
        }
    }
}
