<?php

namespace GravityKit\GravityExport\Save\TokenProvider;

use GravityKit\GravityExport\GuzzleHttp\Exception\ClientException;
use GravityKit\GravityExport\Save\StorageType\Dropbox;
use GravityKit\GravityExport\Spatie\Dropbox\RefreshableTokenProvider;

/**
 * A custom token provider that automatically refreshes the access token.
 * @since $ver$
 */
final class AutoRefreshingTokenProvider implements RefreshableTokenProvider {
	/**
	 * The Dropbox adapter.
	 * @since $ver$
	 * @var Dropbox
	 */
	private $dropbox;

	/**
	 * Creates the token provider.
	 *
	 * @param Dropbox $dropbox The Dropbox adapter.
	 *
	 * @since $ver$
	 */
	public function __construct( Dropbox $dropbox ) {
		$this->dropbox = $dropbox;
	}

	/**
	 * @inheritDoc
	 * @since $ver$
	 */
	public function refresh( ClientException $exception ): bool {
		// We can only refresh the token if the current access token is expired.
		if (
			$exception->getCode() !== 401
			|| strpos( $exception->getMessage(), 'expired_access_token' ) === false
		) {
			return false;
		}

		return $this->dropbox->refreshAccessToken();
	}

	/**
	 * @inheritDoc
	 * @since $ver$
	 */
	public function getToken(): string {
		return $this->dropbox->getAccessToken();
	}
}
