<?php

namespace WeDevs\AppBridge\Core\REST;

use WeDevs\AppBridge\Core\AbstractLicenseManager;
use WP_Error;
use WP_REST_Controller;
use WP_REST_Response;
use WP_REST_Server;

/**
 * Base REST controller for license management.
 *
 * Concrete subclasses set `$namespace` to match their integration's REST
 * namespace and pass the integration's LicenseManager to the constructor.
 *
 * Routes registered (relative to $namespace):
 *   POST /license/activate
 *   POST /license/deactivate
 *   GET  /license/status
 */
abstract class AbstractLicenseController extends WP_REST_Controller {

	protected $rest_base = 'license';

	/**
	 * @var AbstractLicenseManager
	 */
	private $license_manager;

	public function __construct( AbstractLicenseManager $license_manager ) {
		$this->license_manager = $license_manager;
	}

	public function register_routes(): void {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/activate',
			[
				[
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => [ $this, 'activate_license' ],
					'permission_callback' => [ $this, 'permission_callback' ],
				],
			]
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/deactivate',
			[
				[
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => [ $this, 'deactivate_license' ],
					'permission_callback' => [ $this, 'permission_callback' ],
				],
			]
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/status',
			[
				[
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => [ $this, 'license_status' ],
					'permission_callback' => [ $this, 'permission_callback' ],
				],
			]
		);
	}

	/**
	 * @return bool
	 */
	public function permission_callback(): bool {
		return current_user_can( 'manage_options' );
	}

	/**
	 * Activate license.
	 *
	 * @return WP_REST_Response|WP_Error
	 */
	public function activate_license( $request ) {
		if ( empty( $request['license_key'] ) ) {
			return new WP_Error( 'empty-license-key', __( 'License key is required.', 'app-bridge' ), [ 'status' => 400 ] );
		}

		$result = $this->license_manager->activate( $request['license_key'] );

		if ( ! $result['success'] ) {
			return new WP_Error( 'license-error', $result['message'], [ 'status' => 422 ] );
		}

		return rest_ensure_response( $result );
	}

	/**
	 * Deactivate license.
	 *
	 * @return WP_REST_Response|WP_Error
	 */
	public function deactivate_license( $request ) {
		$result = $this->license_manager->deactivate();

		if ( ! $result['success'] ) {
			return new WP_Error( 'license-error', $result['message'], [ 'status' => 422 ] );
		}

		return rest_ensure_response( $result );
	}

	/**
	 * Return license status compatible with the plugin-ui LicenseStatus shape.
	 *
	 * @return WP_REST_Response
	 */
	public function license_status(): WP_REST_Response {
		$license = $this->license_manager->get_license();
		$stored  = $license->get_license();

		return rest_ensure_response(
			[
				'is_valid'    => $license->is_valid(),
				'expiry_days' => isset( $stored['expiry_days'] ) ? (int) $stored['expiry_days'] : null,
				'data'        => [
					'key'              => $stored['key'] ?? '',
					'remaining'        => isset( $stored['remaining'] ) ? (int) $stored['remaining'] : null,
					'activation_limit' => isset( $stored['activation_limit'] ) ? (int) $stored['activation_limit'] : null,
				],
			]
		);
	}
}
