<?php

namespace WPDesk\FakturyKSEF\Api;

use WPDesk\FakturyKSEF\Api\Requests\KsefRequestInterface;
use WPDeskKSEFVendor\GuzzleHttp\Client;
use WPDeskKSEFVendor\GuzzleHttp\Exception\GuzzleException;
use WPDeskKSEFVendor\GuzzleHttp\Exception\RequestException;
use WPDeskKSEFVendor\Psr\Log\LoggerInterface;

class LowLevelAPIClient {

	private Client $http_client;

	private LoggerInterface $logger;

	public function __construct( Client $http_client, LoggerInterface $logger ) {
		$this->http_client = $http_client;
		$this->logger      = $logger;
	}

	public function execute( KsefRequestInterface $request, string $token = '' ): array {
		$headers = [ 'Content-Type' => 'application/json' ];

		if ( ! empty( $token ) ) {
			$headers['Authorization'] = 'Bearer ' . $token;
		}

		try {
			$response = $this->http_client->request(
				$request->get_method(),
				$request->get_uri(),
				[
					'headers' => $headers,
					'json'    => $request->get_body(),
				]
			);

			return json_decode( $response->getBody()->getContents(), true ) ?? [];

		} catch ( RequestException $e ) {
			$this->logger->error( 'KSeF Request Error: ' . $e->getMessage() );
			throw $e;
		} catch ( GuzzleException $e ) {
			$this->logger->error( 'KSeF Guzzle Error: ' . $e->getMessage() );
			throw $e;
		}
	}
}
