<?php

/**
 * WordPress REST callbacks for license endpoints (extracted from LicenseController for S1448).
 */

namespace FleekDash\Controllers\License;

use FleekDash\Controllers\LicenseController;
use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

if (!\function_exists('fleekdash_log_debug')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

final class LicenseRestController
{
    private static ?self $instance = null;

    private LicenseController $license;

    private function __construct(LicenseController $license)
    {
        $this->license = $license;
    }

    public static function getInstance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self(LicenseController::getInstance());
        }

        return self::$instance;
    }

    /**
     * GET: license status for SPA boot (no POST / nonce required).
     *
     * @param WP_REST_Request $request Query params: optional force_check, license_key.
     */
    public function restGetLicenseStatus(WP_REST_Request $request)
    {
        $inner = new WP_REST_Request('POST', '/fleekdash/v1/license/verify');
        $inner->set_param('license_key', $request->get_param('license_key'));
        $inner->set_param(
            'force_check',
            filter_var($request->get_param('force_check'), FILTER_VALIDATE_BOOLEAN),
        );

        return $this->restVerifyLicense($inner);
    }

    /**
     * REST API endpoint to verify a license.
     *
     * @return \WP_REST_Response
     */
    public function restVerifyLicense(WP_REST_Request $request) // NOSONAR php:S1142
    {
        $license_key = $request->get_param('license_key');
        $force = filter_var($request->get_param('force_check'), FILTER_VALIDATE_BOOLEAN);

        if (empty($license_key)) {
            $license_key = \get_option('fleekdash_v2_license_key');

            if (empty($license_key) && !$force) {
                $status = \get_option('fleekdash_v2_license_status', 'inactive');
                $instance_id = \get_option('fleekdash_v2_instance_id', '');

                if ($status === 'active') {
                    $expires_at = $this->license->getLicenseExpirationDisplay();
                    $license_data = \get_option('fleekdash_v2_license_data');
                    $tier_data = $this->license->getTierDataForLicense(
                        \is_array($license_data) ? $license_data : null,
                    );

                    return new WP_REST_Response([
                        'valid' => true,
                        'status' => 'active',
                        'type' => 'regular',
                        'license_key' => $license_key,
                        'instance_id' => $instance_id,
                        'message' => 'License is active (from WordPress)',
                        'source' => 'wordpress_db',
                        'expires_at' => $expires_at,
                        'tier' => $tier_data,
                    ], 200);
                }

                return new WP_REST_Response([
                    'valid' => false,
                    'status' => 'inactive',
                    'message' => 'No active license found',
                    'source' => 'wordpress_db',
                ], 200);
            }
        }

        fleekdash_log_debug(
            'FleekDash V2 REST: Verifying license key: '
            . ($license_key ?: 'none')
            . ', Force: '
            . ($force ? 'yes' : 'no'),
        );

        $result = $this->license->verifyLicense($license_key, $force);

        fleekdash_log_debug('FleekDash V2 REST: Verification result: ' . print_r($result, true));

        if (($result['status'] ?? '') === 'error' && \get_option('fleekdash_v2_license_status', 'inactive') === 'active') {
            $license_data = \get_option('fleekdash_v2_license_data');
            $license_data = \is_array($license_data) ? $license_data : null;
            $license_key_out = (string) ($license_key ?: \get_option('fleekdash_v2_license_key', ''));
            $instance_id_db = \get_option('fleekdash_v2_instance_id', '');
            $expires_at = $this->license->getLicenseExpirationDisplay($license_data);
            $tier_data = $this->license->getTierDataForLicense($license_data);

            return new WP_REST_Response([
                'valid' => true,
                'status' => 'active',
                'type' => 'regular',
                'activation_limit' => ($tier_data ?? [])['max_quantity'] ?? 999,
                'activation_usage' => 1,
                'license_key' => $license_key_out,
                'instance_id' => $instance_id_db !== '' ? $instance_id_db : null,
                'message' => $result['message'] ?? 'License is active (verification unavailable)',
                'cached' => true,
                'remote_activation' => false,
                'expires_at' => $expires_at,
                'tier' => $tier_data,
                'source' => 'wordpress_db_fallback',
            ], 200);
        }

        if ($result['status'] === 'active') {
            $license_data = $result['license_data'] ?? null;
            $expires_at = $this->license->getLicenseExpirationDisplay($license_data);
            $tier_data = $this->license->getTierDataForLicense($license_data);

            fleekdash_log_debug(
                'FleekDash V2: Calculated expiration date: '
                . $expires_at
                . ' for license data: '
                . print_r($license_data, true),
            );

            return new WP_REST_Response([
                'valid' => true,
                'status' => 'active',
                'type' => 'regular',
                'activation_limit' => ($tier_data ?? [])['max_quantity'] ?? 999,
                'activation_usage' => 1,
                'license_key' => $license_key,
                'instance_id' => $result['instance_id'] ?? null,
                'message' => $result['message'] ?? 'License is active',
                'cached' => $result['cached'] ?? false,
                'remote_activation' => $result['remote_activation'] ?? false,
                'expires_at' => $expires_at,
                'tier' => $tier_data,
                'source' => ($result['remote_activation'] ?? false) ? 'remote_activation' : 'verification',
            ], 200);
        }

        return new WP_REST_Response([
            'valid' => false,
            'status' => 'inactive',
            'message' => $result['message'] ?? \FleekDash\Controllers\MSG_LICENSE_INACTIVE,
            'reason' => $result['reason'] ?? 'unknown',
            'error' => $result['error'] ?? false,
            'source' => 'verification',
        ], 200);
    }

    /**
     * @return \WP_REST_Response|\WP_Error
     */
    public function restActivateLicense(WP_REST_Request $request)
    {
        fleekdash_log_debug('FleekDash V2 REST: Received activation request: ' . print_r($request->get_params(), true));

        $result = $this->license->activateLicense($request);

        fleekdash_log_debug('FleekDash V2 REST: Activation result: ' . print_r($result, true));

        return $result;
    }

    /**
     * @return \WP_REST_Response|\WP_Error
     */
    public function restDeactivateLicense(WP_REST_Request $request)
    {
        fleekdash_log_debug('FleekDash V2 REST: Received deactivation request: ' . print_r($request->get_params(), true));

        $result = $this->license->deactivateLicense($request);

        fleekdash_log_debug('FleekDash V2 REST: Deactivation result: ' . print_r($result, true));

        return $result;
    }

    public function restClearCache(WP_REST_Request $request) // NOSONAR php:S1172 - WP REST callback signature
    {
        \delete_option('fleekdash_v2_tier_data');
        \delete_option('fleekdash_v2_license_last_verified');
        $cleared_feature_cache_entries = $this->license->refreshCachesAfterManualLicenseClear();

        fleekdash_log_info('FleekDash V2: License cache cleared manually (tier + verify TTL + features)');

        return new WP_REST_Response([
            'success' => true,
            'message' => 'License cache cleared successfully',
            'cleared_feature_cache_entries' => $cleared_feature_cache_entries,
        ], 200);
    }
}
