<?php

namespace WPDesk\FakturyKSEF\Api;

class AccessTokenService {

	public const ACCESS_TOKEN_TRANSIENT  = 'fiksef_access_token_transient';
	public const REFRESH_TOKEN_TRANSIENT = 'fiksef_refresh_token_transient';

	private const ACCESS_TOKEN_EXPIRATION_IN_SECONDS  = 600;
	private const REFRESH_TOKEN_EXPIRATION_IN_SECONDS = 2419200;

	public function has_access_token(): bool {
		return get_transient( self::ACCESS_TOKEN_TRANSIENT ) !== false;
	}
	public function has_refresh_token(): bool {
		return get_transient( self::REFRESH_TOKEN_TRANSIENT ) !== false;
	}

	public function get_access_token(): string {
		return $this->get_transient( self::ACCESS_TOKEN_TRANSIENT );
	}

	public function get_refresh_token(): string {
		return $this->get_transient( self::REFRESH_TOKEN_TRANSIENT );
	}

	private function get_transient( string $key ): string {
		$transient = get_transient( $key );

		if ( ! $transient ) {
			return '';
		}
		return $transient;
	}

	public function update_access_token( string $new_token ): void {
		set_transient( self::ACCESS_TOKEN_TRANSIENT, $new_token, self::ACCESS_TOKEN_EXPIRATION_IN_SECONDS );
	}
	public function update_refresh_token( string $new_token ): void {
		set_transient( self::REFRESH_TOKEN_TRANSIENT, $new_token, self::REFRESH_TOKEN_EXPIRATION_IN_SECONDS );
	}

	public function clear_tokens(): void {
		delete_transient( self::ACCESS_TOKEN_TRANSIENT );
		delete_transient( self::REFRESH_TOKEN_TRANSIENT );
	}
}
