<?php
//phpcs:disable WordPress

namespace WeeConnectPay\Api;

use WeeConnectPay\Dependencies\GuzzleHttp\Client as Client;
//use GuzzleHttp\Client as Client;
use WeeConnectPay\AccessToken;
use WeeConnectPay\Environment;
use WeeConnectPay\Integrations\IntegrationSettings;
use WeeConnectPay\WordPress\Plugin\includes\WeeConnectPayUtilities;

class ApiClient {
	/**
	 * @var $domain string
	 */
	private $domain;


	/**
	 * @var $client Client
	 */
	public $client;

	/**
	 * @return string
	 */
	public function getDomain(): string {
		return $this->domain;
	}

	/**
	 * @return void
	 */
	private function setDomain(): void {
		$this->domain = Environment::getApiBaseUrl();
	}

	/**
	 * Api constructor. Initializes client.
	 */
	public function __construct() {
		$this->setDomain();


		$this->client = new Client( [
			'base_uri'  => $this->domain,
			'timeout'   => 60,
			'protocols' => [ 'https' ], // https only
			'allow_redirects' => false, // Our API should not redirect, and this client is exclusive to our API
			'headers'   => [
				'Authorization' => "Bearer {$this->maybeAuthKey()}",
				'Content-Type' => 'application/json',
				'Accept'       => 'application/json',
			]
		] );
	}

	/**
	 * Get the access token used by guzzle client or null if it doesn't exist.
	 *
	 * For client_credentials auth, attempts token refresh if nearing expiry.
	 *
	 * @return string|null
	 * @updated 3.19.0
	 */
	private function maybeAuthKey(): ?string {
		$settings = new IntegrationSettings();
		try {
			if ( ! $settings->accessTokenExists() ) {
				return null;
			}

			// For client_credentials auth, attempt token refresh if needed
			if ( $settings->getAuthMethodOrDefault() === 'client_credentials' ) {
				$tokenManager = new \WeeConnectPay\Integrations\OAuthTokenManager();
				$refreshedToken = $tokenManager->refreshTokenIfNeeded();
				if ( $refreshedToken ) {
					return $refreshedToken->getToken();
				}
			}

			return $settings->getAccessToken()->getToken();
		} catch (\Throwable $exception) {
			// Silently fail
			return null;
		}
	}

}
