<?php declare( strict_types=1 );

namespace FernleafSystems\Wordpress\Plugin\Shield\WpCli\Cmds;

use FernleafSystems\Wordpress\Plugin\Shield\Modules\License\Lib\Activate as LicenseActivate;
use FernleafSystems\Wordpress\Plugin\Shield\Modules\License\Lib\Exceptions\LicenseAlreadyActivatedException;
use FernleafSystems\Wordpress\Plugin\Shield\Modules\License\Lib\Verify as LicenseVerify;
use WP_CLI;

class License extends BaseCmd {

	/**
	 * License checking WP-CLI cmds may be run if you're not premium,
	 * or you're premium and you haven't switched it off (parent).
	 */
	protected function canRun() :bool {
		return self::con()->caps->canWpcliLevel1();
	}

	protected function cmdParts() :array {
		return [ 'pro-license' ];
	}

	protected function cmdShortDescription() :string {
		return sprintf( 'Manage the %s license.', self::con()->labels->Name );
	}

	protected function cmdSynopsis() :array {
		return [
			[
				'type'        => 'assoc',
				'name'        => 'action',
				'options'     => [
					'status',
					'verify',
					'remove',
					'activate',
				],
				'default'     => 'status',
				'optional'    => false,
				'description' => sprintf( 'Action to perform on the %s license.', self::con()->labels->Name ),
			],
			[
				'type'        => 'flag',
				'name'        => 'force',
				'optional'    => true,
				'description' => 'Bypass confirmation prompt.',
			],
			[
				'type'        => 'assoc',
				'name'        => 'api-key',
				'optional'    => true,
				'description' => 'API key for license activation (required for activate action).',
			],
		];
	}

	public function runCmd() :void {
		switch ( $this->execCmdArgs[ 'action' ] ) {
			case 'verify':
				$this->runVerify();
				break;
			case 'remove':
				$this->runRemove( $this->isForceFlag() );
				break;
			case 'activate':
				$this->runActivate();
				break;
			case 'status':
			default:
				$this->runStatus();
				break;
		}
	}

	private function runRemove( $confirm ) {
		if ( self::con()->isPremiumActive() ) {
			if ( !$confirm ) {
				WP_CLI::confirm( sprintf( __( 'Are you sure you want to remove the %s license?', 'wp-simple-firewall' ), self::con()->labels->Name ) );
			}
			self::con()->comps->license->clearLicense();
			WP_CLI::success( __( 'License removed successfully.', 'wp-simple-firewall' ) );
		}
		else {
			WP_CLI::success( __( 'No license to remove.', 'wp-simple-firewall' ) );
		}
	}

	private function runStatus() {
		self::con()->comps->license->isActive() ?
			WP_CLI::success( __( 'Active license found.', 'wp-simple-firewall' ) )
			: WP_CLI::error( __( 'No active license present.', 'wp-simple-firewall' ) );
	}

	private function runVerify() {
		try {
			if ( self::con()->isPremiumActive() ) {
				WP_CLI::log( 'Premium license is already active. Re-checking...' );
			}
			$success = self::con()->comps->license->verify( true )->hasValidWorkingLicense();
			$msg = $success ? __( 'Valid license found and installed.', 'wp-simple-firewall' )
				: __( "Valid license couldn't be found.", 'wp-simple-firewall' );
		}
		catch ( \Exception $e ) {
			$success = false;
			$msg = $e->getMessage();
		}

		$success ? WP_CLI::success( $msg ) : WP_CLI::error( $msg );
	}

	private function runActivate() :void {
		$apiKey = $this->execCmdArgs[ 'api-key' ] ?? '';
		$alreadyActivated = false;

		if ( empty( $apiKey ) ) {
			WP_CLI::error( __( 'API key is required for activation. Use --api-key=YOUR_KEY', 'wp-simple-firewall' ) );
		}

		if ( self::con()->isPremiumActive() && !$this->isForceFlag() ) {
			WP_CLI::error( __( 'A license is already active. Use --force to reactivate.', 'wp-simple-firewall' ) );
		}

		try {
			( new LicenseActivate() )->run( $apiKey );
		}
		catch ( LicenseAlreadyActivatedException $e ) {
			$alreadyActivated = true;
			WP_CLI::log( __( 'This site is already activated. Re-checking and syncing local license state...', 'wp-simple-firewall' ) );
		}
		catch ( \Exception $e ) {
			WP_CLI::error( $e->getMessage() );
		}

		try {
			// Run verification directly to avoid activation cooldown checks.
			( new LicenseVerify() )->run();
			$success = self::con()->comps->license->hasValidWorkingLicense();
			$msg = $success
				? (
				$alreadyActivated
					? __( 'Site was already activated and license verified successfully.', 'wp-simple-firewall' )
					: __( 'License activated and verified successfully.', 'wp-simple-firewall' )
				)
				: (
				$alreadyActivated
					? __( 'Site is already activated but license verification failed.', 'wp-simple-firewall' )
					: __( 'License activated but verification failed.', 'wp-simple-firewall' )
				);
		}
		catch ( \Exception $e ) {
			$success = false;
			$msg = $e->getMessage();
		}

		$success ? WP_CLI::success( $msg ) : WP_CLI::error( $msg );
	}
}
