<?php

namespace WPSN\Modules\Licensing;

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

defined('ABSPATH') || exit;

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

    public function __construct(Settings $settings, Logger $logger)
    {
        $this->settings = $settings;
        $this->logger = $logger;
        $this->secrets = new LicenseSecretsRepository();
        $this->cache = new SelfServeManagementCacheRepository();
        $this->billingCache = new BillingSyncCacheRepository();
        $this->catalogCache = new SelfServeUpgradeCacheRepository();
        $this->session = new SelfServeCheckoutSessionRepository();
        $this->client = new SelfServeUpgradeClient($settings, $logger);
        $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 cacheTtlSeconds(): 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 getCache(): ?array
    {
        $cache = $this->cache->get();
        return is_array($cache) ? $cache : null;
    }

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

    /**
     * @return array{ok:bool,verified?:bool,error?:string,trusted?:bool,management?:array<string,mixed>}
     */
    public function fetchStateIfNeeded(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->getCache();
        $checkedAt = $cache && isset($cache['checked_at']) ? (int) $cache['checked_at'] : 0;
        if (!$force && $checkedAt > 0 && (time() - $checkedAt) < $this->cacheTtlSeconds()) {
            return [
                'ok' => true,
                'verified' => false,
                'trusted' => !empty($cache['trusted']),
                'management' => isset($cache['management']) && is_array($cache['management']) ? $cache['management'] : [],
            ];
        }

        $res = $this->client->fetchManagementState($this->secrets->getLicenseKey());
        $now = time();
        if (empty($res['ok'])) {
            $error = isset($res['error']) ? (string) $res['error'] : __('Could not fetch subscription management state.', '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];
        }

        $payload = isset($res['management']) && is_array($res['management']) ? $res['management'] : [];
        $trustedPayload = !empty($payload) ? $payload : (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) {
            $error = __('Self-serve management 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];
        }

        $management = $this->normalizeManagement($payload);
        $this->storeManagement($management, $trusted, (string) ($res['signature'] ?? ''), (string) ($res['alg'] ?? ''));
        $this->storeDerivedBilling($management, $trusted);
        if (!empty($res['catalog']) && is_array($res['catalog'])) {
            $this->storeCatalog($res['catalog'], $trusted, (string) ($res['signature'] ?? ''), (string) ($res['alg'] ?? ''));
        } elseif (!empty($management['plans'])) {
            $this->storeCatalog(['plans' => $management['plans'], 'current_plan' => $management['subscription']['plan_id'] ?? ''], $trusted, (string) ($res['signature'] ?? ''), (string) ($res['alg'] ?? ''));
        }

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

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

        $operation = sanitize_key($operation);
        $allowed = [
            'update_customer',
            'change_plan',
            'update_usage',
            'cancel_now',
            'cancel_at_period_end',
            'resume',
            'set_default_payment_method',
            'remove_payment_method',
            'assign_site',
            'update_site_assignment',
            'release_site',
            'set_primary_site',
            'assign_seat',
            'update_seat_assignment',
            'release_seat',
        ];
        if (!in_array($operation, $allowed, true)) {
            return ['ok' => false, 'error' => __('Unsupported subscription management operation.', 'wp-seo-next')];
        }

        $res = $this->client->performManagementOperation($this->secrets->getLicenseKey(), $operation, $params);
        if (empty($res['ok'])) {
            return ['ok' => false, 'error' => isset($res['error']) ? (string) $res['error'] : __('Subscription management request failed.', 'wp-seo-next')];
        }

        $trustedPayload = [];
        foreach (['management', '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 management payload is unsigned or untrusted.', 'wp-seo-next'), 'trusted' => false];
        }

        $management = [];
        if (!empty($res['management']) && is_array($res['management'])) {
            $management = $this->normalizeManagement($res['management']);
            $this->storeManagement($management, $trusted, (string) ($res['signature'] ?? ''), (string) ($res['alg'] ?? ''));
            $this->storeDerivedBilling($management, $trusted);
        }
        if (!empty($res['billing']) && is_array($res['billing'])) {
            $this->storeBilling($res['billing'], $trusted);
        }
        if (!empty($res['catalog']) && is_array($res['catalog'])) {
            $this->storeCatalog($res['catalog'], $trusted, (string) ($res['signature'] ?? ''), (string) ($res['alg'] ?? ''));
        } elseif (!empty($management['plans'])) {
            $this->storeCatalog(['plans' => $management['plans'], 'current_plan' => $management['subscription']['plan_id'] ?? ''], $trusted, (string) ($res['signature'] ?? ''), (string) ($res['alg'] ?? ''));
        }

        $checkoutSession = null;
        if (!empty($res['checkout']) && is_array($res['checkout'])) {
            $checkoutSession = $this->normalizeCheckoutSession($res['checkout'], isset($management['subscription']['plan_id']) ? (string) $management['subscription']['plan_id'] : '', $trusted);
            if (!empty($checkoutSession['url'])) {
                $this->session->set($checkoutSession);
            }
        }

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

    /**
     * @param array<string,mixed> $payload
     * @return array<string,mixed>
     */
    private function normalizeManagement(array $payload): array
    {
        $customer = isset($payload['customer']) && is_array($payload['customer']) ? $payload['customer'] : [];
        $subscription = isset($payload['subscription']) && is_array($payload['subscription']) ? $payload['subscription'] : $payload;

        $actions = $payload['available_operations'] ?? $payload['allowed_operations'] ?? $payload['actions'] ?? [];
        if (is_string($actions)) {
            $actions = preg_split('/[
,]+/', $actions) ?: [];
        }
        if (!is_array($actions)) {
            $actions = [];
        }
        $normalizedActions = [];
        foreach ($actions as $key => $value) {
            $candidate = '';
            if (is_string($key) && !is_numeric($key)) {
                if ($value === true || $value === 1 || $value === '1' || $value === 'true' || $value === null) {
                    $candidate = sanitize_key($key);
                }
            } elseif (is_scalar($value)) {
                $candidate = sanitize_key((string) $value);
            }
            $candidate = $this->canonicalManagementAction($candidate);
            if ($candidate !== '') {
                $normalizedActions[] = $candidate;
            }
        }

        $plans = $payload['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('/[
,]+/', $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']) : '',
                'current' => !empty($plan['current']),
                'recommended' => !empty($plan['recommended']),
                'features' => array_values(array_filter(array_map('strval', $features))),
            ];
        }

        $methods = $payload['payment_methods'] ?? $payload['paymentMethods'] ?? [];
        if (!is_array($methods)) {
            $methods = [];
        }
        $paymentMethods = [];
        foreach ($methods as $method) {
            if (!is_array($method)) {
                continue;
            }
            $id = $this->firstString([$method], ['id', 'payment_method_id', 'token'], '');
            if ($id === '') {
                continue;
            }
            $brand = strtolower($this->firstString([$method], ['brand', 'type'], ''));
            $last4 = $this->firstString([$method], ['last4'], '');
            $label = $this->firstString([$method], ['label', 'display', 'masked'], '');
            if ($label === '') {
                $label = trim(($brand !== '' ? strtoupper($brand) . ' ' : '') . ($last4 !== '' ? '•••• ' . $last4 : $id));
            }
            $paymentMethods[] = [
                'id' => $id,
                'label' => $label,
                'brand' => $brand,
                'last4' => $last4,
                'exp_month' => $this->firstInt([$method], ['exp_month'], null),
                'exp_year' => $this->firstInt([$method], ['exp_year'], null),
                'is_default' => !empty($method['is_default']) || !empty($method['default']),
                'can_delete' => !isset($method['can_delete']) || !empty($method['can_delete']),
                'status' => $this->firstString([$method], ['status'], ''),
            ];
        }

        $notes = $payload['notes'] ?? $payload['messages'] ?? [];
        if (is_string($notes)) {
            $notes = preg_split('/[
]+/', $notes) ?: [];
        }
        if (!is_array($notes)) {
            $notes = [];
        }
        $normalizedNotes = [];
        foreach ($notes as $note) {
            if (!is_scalar($note)) {
                continue;
            }
            $note = trim((string) $note);
            if ($note !== '') {
                $normalizedNotes[] = $note;
            }
        }

        $siteAssignments = $this->normalizeSiteAssignments($payload);
        $usage = $this->normalizeUsageSummary($payload, $subscription, $siteAssignments);
        $seatAssignments = $this->normalizeSeatAssignments($payload);
        $usageEvents = $this->normalizeUsageEvents($payload);

        $currentAssignmentId = '';
        foreach ($siteAssignments as $assignment) {
            if (!empty($assignment['is_current_site']) && !empty($assignment['id'])) {
                $currentAssignmentId = (string) $assignment['id'];
                break;
            }
        }

        return [
            'customer' => [
                'name' => $this->firstString([$customer, $payload], ['name', 'customer_name'], ''),
                'email' => $this->firstString([$customer, $payload], ['email', 'customer_email'], ''),
                'company' => $this->firstString([$customer, $payload], ['company', 'company_name'], ''),
                'vat_id' => $this->firstString([$customer, $payload], ['vat_id', 'tax_id'], ''),
            ],
            'subscription' => [
                'id' => $this->firstString([$subscription, $payload], ['id', 'subscription_id'], ''),
                'plan_id' => sanitize_key($this->firstString([$subscription, $payload], ['plan_id', 'plan', 'tier'], '')),
                'plan_label' => $this->firstString([$subscription, $payload], ['plan_label', 'plan_name', 'plan'], ''),
                'interval' => sanitize_key($this->firstString([$subscription, $payload], ['interval'], '')),
                'status' => $this->firstString([$subscription, $payload], ['status'], ''),
                'renews_at' => $this->firstString([$subscription, $payload], ['renews_at', 'expires_at', 'current_period_end', 'next_billing_at'], ''),
                'seat_limit' => $usage['seats']['limit'],
                'seat_used' => $usage['seats']['used'],
                'site_limit' => $usage['sites']['limit'],
                'site_used' => $usage['sites']['used'],
                'cancel_at_period_end' => !empty($subscription['cancel_at_period_end']) || !empty($subscription['cancel_at_end']),
                'current_site_assignment_id' => $currentAssignmentId,
            ],
            'usage' => $usage,
            'site_assignments' => $siteAssignments,
            'seat_assignments' => $seatAssignments,
            'usage_events' => $usageEvents,
            'actions' => array_values(array_unique($normalizedActions)),
            'payment_methods' => $paymentMethods,
            'plans' => $normalizedPlans,
            'notes' => array_values(array_unique($normalizedNotes)),
        ];
    }

    /**
     * @param array<string,mixed> $management
     */
    private function storeManagement(array $management, bool $trusted, string $signature, string $alg): void
    {
        $this->cache->set([
            'management' => $management,
            '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> $management
     */
    private function storeDerivedBilling(array $management, bool $trusted): void
    {
        $customer = isset($management['customer']) && is_array($management['customer']) ? $management['customer'] : [];
        $subscription = isset($management['subscription']) && is_array($management['subscription']) ? $management['subscription'] : [];
        $usage = isset($management['usage']) && is_array($management['usage']) ? $management['usage'] : [];
        $siteAssignments = isset($management['site_assignments']) && is_array($management['site_assignments']) ? $management['site_assignments'] : [];
        $seatAssignments = isset($management['seat_assignments']) && is_array($management['seat_assignments']) ? $management['seat_assignments'] : [];

        $domains = [];
        foreach ($siteAssignments as $assignment) {
            if (!is_array($assignment)) {
                continue;
            }
            $domain = isset($assignment['domain']) ? trim((string) $assignment['domain']) : '';
            if ($domain !== '') {
                $domains[] = $domain;
                continue;
            }
            $siteUrl = isset($assignment['site_url']) ? trim((string) $assignment['site_url']) : '';
            $host = $this->normalizeHost($siteUrl);
            if ($host !== '') {
                $domains[] = $host;
            }
        }
        $domains = array_values(array_unique(array_filter($domains)));

        $billing = [
            'plan' => (string) (($subscription['plan_label'] ?? '') !== '' ? $subscription['plan_label'] : ($subscription['plan_id'] ?? '')),
            'subscription_id' => (string) ($subscription['id'] ?? ''),
            'customer_name' => (string) ($customer['name'] ?? ''),
            'customer_email' => (string) ($customer['email'] ?? ''),
            'expires_at' => (string) ($subscription['renews_at'] ?? ''),
            'seat_limit' => $subscription['seat_limit'] ?? null,
            'seat_used' => $usage['seats']['used'] ?? ($subscription['seat_used'] ?? null),
            'site_limit' => $subscription['site_limit'] ?? null,
            'site_count' => $usage['sites']['used'] ?? ($subscription['site_used'] ?? null),
            'domains' => $domains,
            'site_assignments' => $siteAssignments,
            'usage' => $usage,
            'seat_assignments' => $seatAssignments,
            'usage_events' => isset($management['usage_events']) && is_array($management['usage_events']) ? $management['usage_events'] : [],
        ];

        $paymentMethods = isset($management['payment_methods']) && is_array($management['payment_methods']) ? $management['payment_methods'] : [];
        if (!empty($paymentMethods)) {
            $billing['payment_methods'] = $paymentMethods;
        }

        $this->storeBilling($billing, $trusted);
    }

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

    /**
     * @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(),
        ];

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

    /**
     * @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->catalogCache->get();
        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>
     */
    /**
     * @param array<int|string,mixed> $payload
     * @return array<int,array<string,mixed>>
     */
    private function normalizeSiteAssignments(array $payload): array
    {
        $raw = $payload['site_assignments'] ?? $payload['assignments'] ?? $payload['sites'] ?? $payload['domains'] ?? [];
        if (is_string($raw)) {
            $raw = preg_split('/[
,]+/', $raw) ?: [];
        }
        if (!is_array($raw)) {
            $raw = [];
        }

        $currentSiteUrl = home_url('/');
        $currentHost = $this->normalizeHost($currentSiteUrl);
        $assignments = [];
        foreach ($raw as $index => $row) {
            if (is_scalar($row)) {
                $row = ['domain' => (string) $row];
            }
            if (!is_array($row)) {
                continue;
            }
            $siteUrl = $this->firstString([$row], ['site_url', 'url', 'domain_url', 'home_url'], '');
            $domain = $this->firstString([$row], ['domain', 'host', 'site', 'url'], '');
            if ($siteUrl === '' && $domain !== '' && strpos($domain, '://') !== false) {
                $siteUrl = $domain;
            }
            $normalizedDomain = $domain !== '' ? $this->normalizeHost($domain) : '';
            if ($normalizedDomain === '' && $siteUrl !== '') {
                $normalizedDomain = $this->normalizeHost($siteUrl);
            }
            if ($siteUrl === '' && $normalizedDomain !== '') {
                $siteUrl = 'https://' . $normalizedDomain . '/';
            }
            $id = $this->firstString([$row], ['id', 'assignment_id', 'site_id', 'license_site_id'], '');
            if ($id === '' && $normalizedDomain === '' && $siteUrl === '') {
                continue;
            }
            if ($id === '') {
                $id = 'site_' . md5(($siteUrl !== '' ? $siteUrl : $normalizedDomain) . '|' . (string) $index);
            }
            $assignments[] = [
                'id' => $id,
                'site_url' => $siteUrl,
                'domain' => $normalizedDomain,
                'label' => $this->firstString([$row], ['label', 'name', 'title'], ''),
                'status' => $this->firstString([$row], ['status', 'state'], ''),
                'assigned_at' => $this->firstString([$row], ['assigned_at', 'created_at', 'added_at'], ''),
                'last_seen_at' => $this->firstString([$row], ['last_seen_at', 'updated_at', 'checked_at'], ''),
                'notes' => $this->firstString([$row], ['notes', 'note', 'description'], ''),
                'seat_count' => $this->firstInt([$row], ['seat_count', 'seats', 'seat_limit'], null),
                'is_primary' => !empty($row['is_primary']) || !empty($row['primary']) || !empty($row['default']),
                'is_current_site' => ($siteUrl !== '' && rtrim($siteUrl, '/') === rtrim($currentSiteUrl, '/')) || ($normalizedDomain !== '' && $normalizedDomain === $currentHost),
            ];
        }

        usort($assignments, static function (array $a, array $b): int {
            if (!empty($a['is_current_site']) && empty($b['is_current_site'])) {
                return -1;
            }
            if (empty($a['is_current_site']) && !empty($b['is_current_site'])) {
                return 1;
            }
            if (!empty($a['is_primary']) && empty($b['is_primary'])) {
                return -1;
            }
            if (empty($a['is_primary']) && !empty($b['is_primary'])) {
                return 1;
            }
            return strcmp((string) ($a['domain'] ?? ''), (string) ($b['domain'] ?? ''));
        });

        return $assignments;
    }

    /**
     * @param array<int|string,mixed> $payload
     * @param array<string,mixed> $subscription
     * @param array<int,array<string,mixed>> $siteAssignments
     * @return array<string,array<string,int|null>>
     */
    private function normalizeUsageSummary(array $payload, array $subscription, array $siteAssignments): array
    {
        $usage = $payload['usage'] ?? $payload['usage_summary'] ?? [];
        if (!is_array($usage)) {
            $usage = [];
        }
        $seats = isset($usage['seats']) && is_array($usage['seats']) ? $usage['seats'] : $usage;
        $sites = isset($usage['sites']) && is_array($usage['sites']) ? $usage['sites'] : $usage;

        $seatUsed = $this->firstInt([$seats, $usage, $subscription, $payload], ['used', 'seat_used', 'seats_used', 'used_seats'], null);
        $seatLimit = $this->firstInt([$seats, $usage, $subscription, $payload], ['limit', 'seat_limit', 'seats_limit', 'max_seats'], null);
        $siteUsed = $this->firstInt([$sites, $usage, $subscription, $payload], ['used', 'site_used', 'sites_used', 'site_count', 'domain_count'], null);
        $siteLimit = $this->firstInt([$sites, $usage, $subscription, $payload], ['limit', 'site_limit', 'sites_limit', 'domain_limit'], null);

        if ($siteUsed === null && !empty($siteAssignments)) {
            $siteUsed = count($siteAssignments);
        }

        return [
            'seats' => [
                'used' => $seatUsed,
                'limit' => $seatLimit,
                'available' => ($seatUsed !== null && $seatLimit !== null) ? max(0, $seatLimit - $seatUsed) : null,
            ],
            'sites' => [
                'used' => $siteUsed,
                'limit' => $siteLimit,
                'available' => ($siteUsed !== null && $siteLimit !== null) ? max(0, $siteLimit - $siteUsed) : null,
            ],
        ];
    }

    /**
     * @param array<int|string,mixed> $payload
     * @return array<int,array<string,mixed>>
     */
    private function normalizeSeatAssignments(array $payload): array
    {
        $raw = $payload['seat_assignments'] ?? $payload['team_members'] ?? $payload['members'] ?? $payload['users'] ?? [];
        if (!is_array($raw)) {
            return [];
        }

        $currentUserId = function_exists('get_current_user_id') ? (int) get_current_user_id() : 0;
        $currentUserEmail = strtolower((string) get_bloginfo('admin_email'));
        if (function_exists('wp_get_current_user')) {
            $currentUser = wp_get_current_user();
            if (is_object($currentUser) && isset($currentUser->user_email) && is_string($currentUser->user_email) && trim((string) $currentUser->user_email) !== '') {
                $currentUserEmail = strtolower(trim((string) $currentUser->user_email));
            }
        }

        $out = [];
        foreach ($raw as $index => $row) {
            if (!is_array($row)) {
                continue;
            }

            $email = strtolower($this->firstString([$row], ['email', 'user_email'], ''));
            $name = $this->firstString([$row], ['name', 'display_name', 'full_name'], '');
            if ($email === '' && $name === '') {
                continue;
            }

            $userId = $this->firstInt([$row], ['user_id', 'wp_user_id'], null);
            $status = $this->firstString([$row], ['status', 'state'], '');
            $role = $this->firstString([$row], ['role', 'seat_role', 'team_role', 'label'], '');
            $siteAssignmentId = $this->firstString([$row], ['site_assignment_id', 'site_id', 'assignment_id'], '');

            $out[] = [
                'id' => $this->firstString([$row], ['id', 'seat_id', 'assignment_id'], 'seat_' . (string) $index),
                'email' => $email,
                'name' => $name,
                'status' => $status,
                'role' => $role,
                'notes' => $this->firstString([$row], ['notes', 'note', 'description'], ''),
                'assigned_at' => $this->firstString([$row], ['assigned_at', 'created_at', 'added_at'], ''),
                'last_seen_at' => $this->firstString([$row], ['last_seen_at', 'last_active_at', 'updated_at'], ''),
                'seat_count' => $this->firstInt([$row], ['seat_count', 'seats'], null),
                'site_assignment_id' => $siteAssignmentId,
                'user_id' => $userId,
                'is_current_user' => ($userId !== null && $currentUserId > 0 && $userId === $currentUserId) || ($email !== '' && $currentUserEmail !== '' && $email === $currentUserEmail),
            ];
        }

        usort($out, static function (array $a, array $b): int {
            if (!empty($a['is_current_user']) && empty($b['is_current_user'])) {
                return -1;
            }
            if (empty($a['is_current_user']) && !empty($b['is_current_user'])) {
                return 1;
            }
            return strcmp((string) ($a['email'] ?? ''), (string) ($b['email'] ?? ''));
        });

        return $out;
    }

    /**
     * @param array<int|string,mixed> $payload
     * @return array<int,array<string,string>>
     */
    private function normalizeUsageEvents(array $payload): array
    {
        $raw = $payload['usage_events'] ?? $payload['site_events'] ?? $payload['assignment_events'] ?? $payload['history'] ?? [];
        if (!is_array($raw)) {
            return [];
        }
        $events = [];
        foreach ($raw as $row) {
            if (!is_array($row)) {
                continue;
            }
            $date = $this->firstString([$row], ['date', 'created_at', 'timestamp', 'at'], '');
            $kind = $this->firstString([$row], ['kind', 'type', 'event'], '');
            $summary = $this->firstString([$row], ['summary', 'message', 'label', 'description'], '');
            if ($date === '' && $kind === '' && $summary === '') {
                continue;
            }
            $events[] = [
                'date' => $date,
                'kind' => $kind,
                'summary' => $summary,
                'value' => $this->firstString([$row], ['value', 'domain', 'site_url'], ''),
            ];
            if (count($events) >= 20) {
                break;
            }
        }
        return $events;
    }

    private function canonicalManagementAction(string $action): string
    {
        $action = sanitize_key($action);
        $aliases = [
            'remove_site_assignment' => 'release_site',
            'delete_site_assignment' => 'release_site',
            'site_release' => 'release_site',
            'assign_current_site' => 'assign_site',
            'site_assign' => 'assign_site',
            'update_site' => 'update_site_assignment',
            'edit_site_assignment' => 'update_site_assignment',
            'make_primary_site' => 'set_primary_site',
            'set_default_site' => 'set_primary_site',
            'seat_assign' => 'assign_seat',
            'add_seat' => 'assign_seat',
            'invite_member' => 'assign_seat',
            'update_seat' => 'update_seat_assignment',
            'edit_seat_assignment' => 'update_seat_assignment',
            'update_member' => 'update_seat_assignment',
            'seat_release' => 'release_seat',
            'remove_seat_assignment' => 'release_seat',
            'delete_seat_assignment' => 'release_seat',
        ];
        return $aliases[$action] ?? $action;
    }

    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);
    }

    /**
     * @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<int,array<string,mixed>> $sources
     * @param array<int,string> $keys
     */
    private function firstString(array $sources, array $keys, string $default = ''): string
    {
        foreach ($sources as $source) {
            foreach ($keys as $key) {
                if (!isset($source[$key]) || !is_scalar($source[$key])) {
                    continue;
                }
                $value = trim((string) $source[$key]);
                if ($value !== '') {
                    return $value;
                }
            }
        }

        return $default;
    }

    /**
     * @param array<int,array<string,mixed>> $sources
     * @param array<int,string> $keys
     */
    private function firstInt(array $sources, array $keys, ?int $default = null): ?int
    {
        foreach ($sources as $source) {
            foreach ($keys as $key) {
                if (!isset($source[$key]) || !is_numeric($source[$key])) {
                    continue;
                }
                return (int) $source[$key];
            }
        }

        return $default;
    }
}
