<?php

namespace Planaday\Api\V1;

use Planaday\Api\ApiException\ApiErrorResponseException;
use Planaday\Api\ApiException\ClientNotInitializedException;
use Planaday\Api\RegistrationApi;
use Planaday\Config\General\Debug\DebugSettings;
use Planaday\Platform\PlatformAbstraction\DataHandler;
use Planaday\Platform\PlatformAbstraction\UrlHandler;
use Planaday\Utility\DataFilters\InvalidException;
use Planaday\Utility\DataFilters\TypeValidator;
use Planaday\Utility\Debug\Log\Logging;
use Planaday\Utility\PluginData;

class RegistrationApiV1 implements RegistrationApi{
	use Logging;

	public function __construct(
		protected ClientV1 $client,
		protected PluginData $pluginData,
		protected UrlHandler $urlHandler,
		protected DataHandler $dataHandler,
		protected TypeValidator $typeValidator,
		protected DebugSettings $debugSettings
	) {}

	public function register(): void {
		if($this->debugSettings->isUrlRegistration() === false) {
			$this->logInfo("RegistrationApiV1 registration skipped (disabled in debug settings)");
			return;
		}

		try {
			$result = $this->client->callEndpoint(
				'register',
				[],
				'POST',
				[
					'url' => $this->urlHandler->getBaseUrl(),
					'wordpress_version' => $this->dataHandler->getPlatformVersion(),
					'connector_version' => implode('.', $this->pluginData->getPluginVersion()),
					'php_version' => phpversion(),
				]
			);
		} catch ( ApiErrorResponseException|ClientNotInitializedException ) {
			return;
		}

		try {
			$key = $this->getKeyFromResponse( $result->getData() );
		} catch ( InvalidException ) {
			$this->logError( "could not parse response from server to registration", $result);
			return;
		}

		$this->dataHandler->saveBackofficeKey( $key );
	}

	/**
	 * @throws InvalidException
	 */
	private function getKeyFromResponse(mixed $response):string {
		$response = $this->typeValidator->array( $response ) ?? [];
		return $this->typeValidator->str( $response['key'] ?? throw new InvalidException("key was not set"));
	}
}