<?php

namespace WPSN\Modules\Licensing;

use WPSN\Core\Logger;
use WPSN\Core\Settings;

defined('ABSPATH') || exit;

final class SelfServeUpgradeService
{
    private Settings $settings;
    private Logger $logger;
    private LicenseSecretsRepository $secrets;
    private SelfServeUpgradeCacheRepository $cache;
    private SelfServeCheckoutSessionRepository $session;
    private SelfServeUpgradeClient $client;
    private BillingSyncCacheRepository $billingCache;
    private LicenseSignatureVerifier $sig;

    public function __construct(Settings $settings, Logger $logger)
    {
        $this->settings = $settings;
        $this->logger = $logger;
        $this->secrets = new LicenseSecretsRepository();
        $this->cache = new SelfServeUpgradeCacheRepository();
        $this->session = new SelfServeCheckoutSessionRepository();
        $this->client = new SelfServeUpgradeClient($settings, $logger);
        $this->billingCache = new BillingSyncCacheRepository();
        $this->sig = new LicenseSignatureVerifier($settings);
    }

    public function isEnabled(): bool
    {
        return (bool) $this->settings->get('licensing.self_serve_enabled', false);
    }

    public function requireSigned(): bool
    {
        return (bool) $this->settings->get('licensing.self_serve_require_signed', false);
    }

    public function hasLicenseKey(): bool
    {
        return $this->secrets->hasLicenseKey();
    }

    public function catalogTtlSeconds(): int
    {
        $hours = (int) $this->settings->get('licensing.self_serve_cache_ttl_hours', 6);
        $hours = max(1, min(168, $hours));
        return $hours * HOUR_IN_SECONDS;
    }

    /**
     * @return array<string,mixed>|null
     */
    public function getCatalogCache(): ?array
    {
        $cache = $this->cache->get();
        return is_array($cache) ? $cache : null;
    }

    public function clearCatalogCache(): void
    {
        $this->cache->clear();
    }

    /**
     * @return array<string,mixed>|null
     */
    public function getCheckoutSession(): ?array
    {
        $session = $this->session->get();
        return is_array($session) ? $session : null;
    }

    public function clearCheckoutSession(): void
    {
        $this->session->clear();
    }

    /**
     * @return array{ok:bool,verified?:bool,error?:string,trusted?:bool,catalog?:array<string,mixed>}
     */
    public function fetchCatalogIfNeeded(bool $force = false): array
    {
        if (!$this->isEnabled()) {
            return ['ok' => true, 'verified' => false];
        }

        if (!$this->hasLicenseKey()) {
            return ['ok' => false, 'verified' => false, 'error' => __('License key is empty.', 'wp-seo-next')];
        }

        $cache = $this->getCatalogCache();
        $checkedAt = $cache && isset($cache['checked_at']) ? (int) $cache['checked_at'] : 0;
        if (!$force && $checkedAt > 0 && (time() - $checkedAt) < $this->catalogTtlSeconds()) {
            return [
                'ok' => true,
                'verified' => false,
                'trusted' => !empty($cache['trusted']),
                'catalog' => isset($cache['catalog']) && is_array($cache['catalog']) ? $cache['catalog'] : [],
            ];
        }

        $res = $this->client->fetchCatalog($this->secrets->getLicenseKey());
        $now = time();
        if (empty($res['ok'])) {
            $error = isset($res['error']) ? (string) $res['error'] : __('Could not fetch self-serve plans.', 'wp-seo-next');
            $newCache = is_array($cache) ? $cache : [];
            $newCache['checked_at'] = $now;
            $newCache['status'] = 'failed';
            $newCache['last_error'] = $error;
            $this->cache->set($newCache);
            return ['ok' => false, 'verified' => false, 'error' => $error];
        }

        $catalog = isset($res['catalog']) && is_array($res['catalog']) ? $this->normalizeCatalog($res['catalog']) : [];
        $trusted = $this->verifyPayload($catalog, (string) ($res['signature'] ?? ''), (string) ($res['alg'] ?? ''), (string) ($res['kid'] ?? ''));
        $this->persistConnection(isset($res['connection']) && is_array($res['connection']) ? $res['connection'] : [], $trusted);
        if ($this->requireSigned() && !$trusted) {
            $error = __('Self-serve catalog payload is unsigned or untrusted.', 'wp-seo-next');
            $newCache = is_array($cache) ? $cache : [];
            $newCache['checked_at'] = $now;
            $newCache['status'] = 'untrusted';
            $newCache['last_error'] = $error;
            $this->cache->set($newCache);
            return ['ok' => false, 'verified' => false, 'error' => $error, 'trusted' => false];
        }

        $newCache = [
            'catalog' => $catalog,
            'signature' => isset($res['signature']) ? (string) $res['signature'] : '',
            'alg' => isset($res['alg']) ? (string) $res['alg'] : '',
            'trusted' => $trusted,
            'status' => 'ok',
            'checked_at' => $now,
            'last_error' => '',
            'last_success_at' => $now,
        ];
        $this->cache->set($newCache);

        return ['ok' => true, 'verified' => true, 'trusted' => $trusted, 'catalog' => $catalog];
    }

    /**
     * @return array{ok:bool,error?:string,trusted?:bool,checkout?:array<string,mixed>,message?:string}
     */
    public function startCheckout(string $planId, string $interval = '', string $coupon = ''): array
    {
        if (!$this->isEnabled()) {
            return ['ok' => false, 'error' => __('Self-serve upgrade flow is disabled.', 'wp-seo-next')];
        }
        if (!$this->hasLicenseKey()) {
            return ['ok' => false, 'error' => __('License key is empty.', 'wp-seo-next')];
        }
        $planId = sanitize_key($planId);
        if ($planId === '') {
            return ['ok' => false, 'error' => __('Choose a plan first.', 'wp-seo-next')];
        }

        $res = $this->client->startCheckout($this->secrets->getLicenseKey(), $planId, $interval, $coupon);
        if (empty($res['ok'])) {
            return ['ok' => false, 'error' => isset($res['error']) ? (string) $res['error'] : __('Could not start checkout.', 'wp-seo-next')];
        }

        $checkout = isset($res['checkout']) && is_array($res['checkout']) ? $res['checkout'] : [];
        $trustedPayload = !empty($checkout) ? $checkout : (isset($res['raw']) && is_array($res['raw']) ? $res['raw'] : []);
        $trusted = $this->verifyPayload($trustedPayload, (string) ($res['signature'] ?? ''), (string) ($res['alg'] ?? ''), (string) ($res['kid'] ?? ''));
        $this->persistConnection(isset($res['connection']) && is_array($res['connection']) ? $res['connection'] : [], $trusted);
        if ($this->requireSigned() && !$trusted) {
            return ['ok' => false, 'error' => __('Self-serve checkout payload is unsigned or untrusted.', 'wp-seo-next'), 'trusted' => false];
        }

        if (!empty($res['catalog']) && is_array($res['catalog'])) {
            $this->storeCatalog($res['catalog'], $trusted, (string) ($res['signature'] ?? ''), (string) ($res['alg'] ?? ''));
        }
        if (!empty($res['billing']) && is_array($res['billing'])) {
            $this->storeBilling($res['billing'], $trusted);
        }

        $session = $this->normalizeCheckoutSession($checkout, $planId, $trusted);
        if (empty($session['url'])) {
            return ['ok' => false, 'error' => __('Checkout response did not include a usable URL.', 'wp-seo-next')];
        }
        $this->session->set($session);

        return [
            'ok' => true,
            'trusted' => $trusted,
            'checkout' => $session,
            'message' => isset($res['message']) ? (string) $res['message'] : '',
        ];
    }

    /**
     * @return array{ok:bool,error?:string,trusted?:bool,message?:string,checkout?:array<string,mixed>}
     */
    public function performAction(string $action, string $planId = '', string $interval = ''): array
    {
        if (!$this->isEnabled()) {
            return ['ok' => false, 'error' => __('Self-serve upgrade flow is disabled.', 'wp-seo-next')];
        }
        if (!$this->hasLicenseKey()) {
            return ['ok' => false, 'error' => __('License key is empty.', 'wp-seo-next')];
        }

        $action = sanitize_key($action);
        if (!in_array($action, ['cancel', 'resume', 'change_plan', 'upgrade', 'downgrade'], true)) {
            return ['ok' => false, 'error' => __('Unsupported self-serve action.', 'wp-seo-next')];
        }

        $res = $this->client->performAction($this->secrets->getLicenseKey(), $action, $planId, $interval);
        if (empty($res['ok'])) {
            return ['ok' => false, 'error' => isset($res['error']) ? (string) $res['error'] : __('Self-serve action failed.', 'wp-seo-next')];
        }

        $trustedPayload = [];
        foreach (['billing', 'catalog', 'checkout'] as $key) {
            if (!empty($res[$key]) && is_array($res[$key])) {
                $trustedPayload = $res[$key];
                break;
            }
        }
        if (empty($trustedPayload) && isset($res['raw']) && is_array($res['raw'])) {
            $trustedPayload = $res['raw'];
        }

        $trusted = $this->verifyPayload($trustedPayload, (string) ($res['signature'] ?? ''), (string) ($res['alg'] ?? ''), (string) ($res['kid'] ?? ''));
        $this->persistConnection(isset($res['connection']) && is_array($res['connection']) ? $res['connection'] : [], $trusted);
        if ($this->requireSigned() && !$trusted) {
            return ['ok' => false, 'error' => __('Self-serve action payload is unsigned or untrusted.', 'wp-seo-next'), 'trusted' => false];
        }

        if (!empty($res['catalog']) && is_array($res['catalog'])) {
            $this->storeCatalog($res['catalog'], $trusted, (string) ($res['signature'] ?? ''), (string) ($res['alg'] ?? ''));
        }
        if (!empty($res['billing']) && is_array($res['billing'])) {
            $this->storeBilling($res['billing'], $trusted);
        }

        $checkoutSession = null;
        if (!empty($res['checkout']) && is_array($res['checkout'])) {
            $checkoutSession = $this->normalizeCheckoutSession($res['checkout'], $planId, $trusted);
            if (!empty($checkoutSession['url'])) {
                $this->session->set($checkoutSession);
            }
        }

        return [
            'ok' => true,
            'trusted' => $trusted,
            'message' => isset($res['message']) ? (string) $res['message'] : '',
            'checkout' => $checkoutSession,
        ];
    }

    /**
     * @param array<string,mixed> $catalog
     */
    private function storeCatalog(array $catalog, bool $trusted, string $signature, string $alg): void
    {
        $catalog = $this->normalizeCatalog($catalog);
        $this->cache->set([
            'catalog' => $catalog,
            'signature' => $signature,
            'alg' => $alg,
            'trusted' => $trusted,
            'status' => 'ok',
            'checked_at' => time(),
            'last_error' => '',
            'last_success_at' => time(),
        ]);
    }

    /**
     * @param array<string,mixed> $billing
     */
    private function storeBilling(array $billing, bool $trusted): void
    {
        $current = $this->billingCache->get();
        if (!is_array($current)) {
            $current = [];
        }
        $current['billing'] = $billing;
        $current['trusted'] = $trusted;
        $current['status'] = 'ok';
        $current['checked_at'] = time();
        $current['last_success_at'] = time();
        $current['last_error'] = '';
        $this->billingCache->set($current);
    }

    /**
     * @param array<string,mixed> $payload
     */
    private function verifyPayload(array $payload, string $signature, string $alg, string $kid = ''): bool
    {
        if (trim($signature) === '') {
            return false;
        }
        return $this->sig->verify($payload, $signature, $alg, $kid);
    }

    /**
     * @param array<string,string> $connection
     */
    private function persistConnection(array $connection, bool $trusted): void
    {
        if (empty($connection)) {
            return;
        }

        if (!$trusted) {
            unset($connection['request_secret']);
        }

        if (empty($connection)) {
            return;
        }

        $this->secrets->updateServerBinding($connection);
    }

    /**
     * @param array<string,mixed> $catalog
     * @return array<string,mixed>
     */
    private function normalizeCatalog(array $catalog): array
    {
        $plans = $catalog['plans'] ?? [];
        if (!is_array($plans)) {
            $plans = [];
        }

        $normalizedPlans = [];
        foreach ($plans as $plan) {
            if (!is_array($plan)) {
                continue;
            }
            $id = isset($plan['id']) ? sanitize_key((string) $plan['id']) : '';
            if ($id === '') {
                continue;
            }
            $features = $plan['features'] ?? [];
            if (is_string($features)) {
                $features = preg_split('/[\r\n,]+/', $features) ?: [];
            }
            if (!is_array($features)) {
                $features = [];
            }
            $normalizedPlans[] = [
                'id' => $id,
                'label' => isset($plan['label']) ? trim((string) $plan['label']) : ucfirst($id),
                'description' => isset($plan['description']) ? trim((string) $plan['description']) : '',
                'price' => isset($plan['price']) ? trim((string) $plan['price']) : '',
                'currency' => strtoupper(isset($plan['currency']) ? (string) $plan['currency'] : ''),
                'interval' => isset($plan['interval']) ? sanitize_key((string) $plan['interval']) : '',
                'action' => isset($plan['action']) ? sanitize_key((string) $plan['action']) : '',
                'recommended' => !empty($plan['recommended']),
                'current' => !empty($plan['current']),
                'features' => array_values(array_filter(array_map('strval', $features))),
            ];
        }

        $catalog['plans'] = $normalizedPlans;
        $catalog['current_plan'] = isset($catalog['current_plan']) ? sanitize_key((string) $catalog['current_plan']) : '';
        $catalog['currency'] = strtoupper(isset($catalog['currency']) ? (string) $catalog['currency'] : '');
        $catalog['interval'] = isset($catalog['interval']) ? sanitize_key((string) $catalog['interval']) : '';

        return $catalog;
    }

    /**
     * @param array<string,mixed> $checkout
     * @return array<string,mixed>
     */
    private function normalizeCheckoutSession(array $checkout, string $planId, bool $trusted): array
    {
        $url = '';
        foreach (['embed_url', 'checkout_url', 'url', 'hosted_url'] as $key) {
            if (!empty($checkout[$key]) && is_scalar($checkout[$key])) {
                $url = trim((string) $checkout[$key]);
                break;
            }
        }

        $session = [
            'url' => $url,
            'plan_id' => sanitize_key($planId !== '' ? $planId : (string) ($checkout['plan_id'] ?? '')),
            'session_id' => isset($checkout['session_id']) ? trim((string) $checkout['session_id']) : '',
            'message' => isset($checkout['message']) ? trim((string) $checkout['message']) : '',
            'trusted' => $trusted,
            'created_at' => time(),
        ];

        $embed = $this->buildEmbedConfig($url);
        return array_merge($session, $embed);
    }

    /**
     * @return array<string,mixed>
     */
    private function buildEmbedConfig(string $url): array
    {
        $height = (int) $this->settings->get('licensing.billing_embed_height', 980);
        $height = max(480, min(2000, $height));

        $allowedHosts = $this->normalizeHosts($this->settings->get('licensing.billing_embed_allowed_hosts', []));
        $serverHost = $this->normalizeHost((string) $this->settings->get('licensing.server_url', ''));
        if ($serverHost !== '' && !in_array($serverHost, $allowedHosts, true)) {
            $allowedHosts[] = $serverHost;
        }

        $catalogCache = $this->getCatalogCache();
        if ($catalogCache && isset($catalogCache['catalog']['checkout_embed_allowed_hosts']) && is_array($catalogCache['catalog']['checkout_embed_allowed_hosts'])) {
            foreach ($catalogCache['catalog']['checkout_embed_allowed_hosts'] as $host) {
                $host = $this->normalizeHost((string) $host);
                if ($host !== '' && !in_array($host, $allowedHosts, true)) {
                    $allowedHosts[] = $host;
                }
            }
        }

        $host = $this->normalizeHost($url);
        $canEmbed = false;
        $reason = '';
        if (!(bool) $this->settings->get('licensing.billing_embed', false)) {
            $reason = 'disabled';
        } elseif ($url === '') {
            $reason = 'missing_url';
        } elseif ($host === '') {
            $reason = 'invalid_url';
        } elseif (in_array($host, $allowedHosts, true)) {
            $canEmbed = true;
        } else {
            $reason = 'host_not_allowlisted';
        }

        return [
            'can_embed' => $canEmbed,
            'embed_reason' => $reason,
            'embed_height' => $height,
            'embed_host' => $host,
        ];
    }

    /**
     * @param mixed $hosts
     * @return array<int,string>
     */
    private function normalizeHosts($hosts): array
    {
        if (is_string($hosts)) {
            $hosts = preg_split('/[\r\n,]+/', $hosts) ?: [];
        }
        if (!is_array($hosts)) {
            return [];
        }
        $out = [];
        foreach ($hosts as $host) {
            $normalized = $this->normalizeHost((string) $host);
            if ($normalized !== '') {
                $out[] = $normalized;
            }
        }
        return array_values(array_unique($out));
    }

    private function normalizeHost(string $value): string
    {
        $value = trim($value);
        if ($value === '') {
            return '';
        }

        $host = wp_parse_url($value, PHP_URL_HOST);
        if (!is_string($host) || $host === '') {
            if (preg_match('/^[A-Za-z0-9.-]+$/', $value)) {
                $host = $value;
            } else {
                return '';
            }
        }
        return strtolower($host);
    }
}
