<?php

namespace WPDesk\FakturyKSEF\Api;

use WPDesk\FakturyKSEF\Api\Requests\KsefRequestInterface;
use WPDesk\FakturyKSEF\Api\Services\AuthService;

class APIClient {

	private LowLevelAPIClient $http_client;

	private AuthService $auth;

	public function __construct(
		LowLevelAPIClient $low_level_api_client,
		AuthService $auth
	) {
		$this->auth        = $auth;
		$this->http_client = $low_level_api_client;
	}

	public function authenticate( bool $force_new_session = false ): bool {
		return $this->auth->authenticate( $force_new_session );
	}

	public function execute( KsefRequestInterface $request, string $token = '' ): array {
		if ( $request->requires_auth() && ! $this->auth->has_access_token() && empty( $token ) ) {
			$this->auth->authenticate();
		}

		if ( empty( $token ) ) {
			$token = $this->auth->get_access_token();
		}

		return $this->http_client->execute( $request, $token );
	}
}
