<?php

declare(strict_types=1);

namespace FormConnector\API\Endpoints;

use FormConnector\Features\License\License;

/**
 * License REST API endpoints.
 */
class LicenseEndpoints {

	private const NAMESPACE = 'fc/v1';

	/**
	 * Register license routes.
	 */
	public static function register(): void {
		register_rest_route(self::NAMESPACE, '/license/status', [
			'methods' => \WP_REST_Server::READABLE,
			'callback' => [self::class, 'get_status'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/license/verify', [
			'methods' => \WP_REST_Server::CREATABLE,
			'callback' => [self::class, 'verify'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/license/activate', [
			'methods' => \WP_REST_Server::CREATABLE,
			'callback' => [self::class, 'activate'],
			'permission_callback' => [self::class, 'permission_check'],
			'args' => [
				'license_key' => [
					'required' => true,
					'type' => 'string',
					'sanitize_callback' => 'sanitize_text_field',
				],
			],
		]);

		register_rest_route(self::NAMESPACE, '/license/deactivate', [
			'methods' => \WP_REST_Server::CREATABLE,
			'callback' => [self::class, 'deactivate'],
			'permission_callback' => [self::class, 'permission_check'],
		]);
	}

	/**
	 * Permission check for admin-only endpoints.
	 */
	public static function permission_check(): bool {
		return current_user_can('manage_options');
	}

	/**
	 * Get license status.
	 */
	public static function get_status(\WP_REST_Request $request): \WP_REST_Response {
		$license = new License();
		
		return new \WP_REST_Response([
			'success' => true,
			'data' => $license->get_status(),
		], 200);
	}

	/**
	 * Verify/refresh license status by re-checking with the API.
	 */
	public static function verify(\WP_REST_Request $request): \WP_REST_Response {
		$license = new License();
		$key = $license->get_key();

		if (empty($key)) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __('No license key configured.', 'form-connector'),
			], 400);
		}

		// Force a refresh by re-validating the existing key
		$license->clear_validation_cache();
		$result = $license->validate($key);

		if ($result['success']) {
			return new \WP_REST_Response([
				'success' => true,
				'message' => __('License verified successfully.', 'form-connector'),
				'data' => $license->get_status(),
			], 200);
		}

		return new \WP_REST_Response([
			'success' => false,
			'message' => $result['error'] ?? __('License verification failed.', 'form-connector'),
			'data' => $license->get_status(),
		], 200); // Still return 200 so frontend can show updated status
	}

	/**
	 * Activate a license key.
	 */
	public static function activate(\WP_REST_Request $request): \WP_REST_Response {
		$key = $request->get_param('license_key');
		$license = new License();
		$license->clear_validation_cache();
		$result = $license->validate($key);

		if ($result['success']) {
			return new \WP_REST_Response([
				'success' => true,
				'message' => __('License activated successfully.', 'form-connector'),
				'data' => $license->get_status(),
			], 200);
		}

		return new \WP_REST_Response([
			'success' => false,
			'message' => $result['error'] ?? __('License activation failed.', 'form-connector'),
		], 400);
	}

	/**
	 * Deactivate the current license.
	 */
	public static function deactivate(\WP_REST_Request $request): \WP_REST_Response {
		$license = new License();
		$license->clear_validation_cache();
		$result = $license->deactivate();

		if ($result['success']) {
			return new \WP_REST_Response([
				'success' => true,
				'message' => $result['message'],
				'data' => $license->get_status(),
			], 200);
		}

		return new \WP_REST_Response([
			'success' => false,
			'message' => $result['error'],
		], 400);
	}
}
