<?php

namespace WeDevs\AppBridge\Core\License;

use WeDevs\AppBridge\Core\Contracts\LicenseBackend;
use WeDevs\AppBridge\ThirdParty\Packages\Appsero\Client;
use WeDevs\AppBridge\ThirdParty\Packages\Appsero\Updater;

/**
 * Appsero-backed license transport.
 *
 * Wraps the Appsero Client / License / Updater stack. This is the default
 * backend and preserves the original AbstractLicenseManager behaviour for
 * every integration whose product is sold through Appsero (Dokan Vendor
 * App, Pocket Store, WP Project Manager).
 */
class AppseroBackend implements LicenseBackend {

	/**
	 * Appsero License object.
	 *
	 * Untyped to avoid Intelephense false-positives from Mozart-scoped
	 * namespaces.
	 *
	 * @var \WeDevs\AppBridge\ThirdParty\Packages\Appsero\License
	 */
	private $license;

	/**
	 * Option key used to persist license data.
	 *
	 * @var string
	 */
	private $option_key;

	/**
	 * @param string $hash_id     Appsero product hash ID.
	 * @param string $plugin_name Human-readable plugin name.
	 * @param string $plugin_file Absolute path to the plugin main file.
	 * @param string $option_key  Option key used to persist license data.
	 */
	public function __construct( string $hash_id, string $plugin_name, string $plugin_file, string $option_key ) {
		$this->option_key = $option_key;

		$client = new Client( $hash_id, $plugin_name, $plugin_file );
		$client->insights()->init_plugin();
		new Updater( $client );

		$this->license = $client->license();
		$this->license->set_option_key( $option_key );
	}

	/**
	 * @inheritDoc
	 */
	public function activate( string $license_key ): array {
		$response = $this->license->activate( $license_key );

		if ( empty( $response['success'] ) ) {
			return [
				'success' => false,
				'message' => $response['error'] ?? __( 'Unknown error occurred.', 'app-bridge' ),
			];
		}

		update_option(
			$this->option_key,
			[
				'key'              => $license_key,
				'status'           => 'activate',
				'remaining'        => $response['remaining'] ?? null,
				'activation_limit' => $response['activation_limit'] ?? null,
				'expiry_days'      => $response['expiry_days'] ?? null,
				'title'            => $response['title'] ?? '',
				'source_id'        => $response['source_identifier'] ?? '',
				'recurring'        => $response['recurring'] ?? false,
			],
			false
		);

		return [
			'success' => true,
			'message' => __( 'License activated successfully.', 'app-bridge' ),
		];
	}

	/**
	 * @inheritDoc
	 */
	public function deactivate( string $license_key ): array {
		$response = $this->license->deactivate( $license_key );

		// Always clear stored data on deactivation attempt.
		update_option(
			$this->option_key,
			[
				'key'    => '',
				'status' => 'deactivate',
			],
			false
		);

		if ( empty( $response['success'] ) ) {
			return [
				'success'   => false,
				'message'   => $response['error'] ?? __( 'Unknown error occurred.', 'app-bridge' ),
				'api_error' => $response['error'] ?? '',
			];
		}

		return [
			'success' => true,
			'message' => __( 'License deactivated successfully.', 'app-bridge' ),
		];
	}

	/**
	 * @inheritDoc
	 */
	public function is_valid(): bool {
		return $this->license->is_valid();
	}

	/**
	 * @inheritDoc
	 */
	public function get_license(): array {
		$stored = $this->license->get_license();

		return is_array( $stored ) ? $stored : [];
	}
}
