<?php

namespace WPSN\Modules\Licensing;

use WPSN\Core\Http\HttpClient;
use WPSN\Core\Logger;
use WPSN\Core\Settings;

defined('ABSPATH') || exit;

final class LicenseClient
{
    private Settings $settings;
    private Logger $logger;
    private ServerContract $contract;

    public function __construct(Settings $settings, Logger $logger)
    {
        $this->settings = $settings;
        $this->logger = $logger;
        $this->contract = new ServerContract($settings);
    }

    /**
     * Remote license verification.
     *
     * @return array{ok:bool,status?:int,error?:string,retry_after?:int,license?:array<string,mixed>,signature?:string,alg?:string,raw?:array<string,mixed>,meta?:array<string,string>,connection?:array<string,string>,kid?:string}
     */
    public function verify(string $licenseKey): array
    {
        $licenseKey = trim($licenseKey);
        if ($licenseKey === '') {
            return ['ok' => false, 'status' => 400, 'error' => __('License key is empty.', 'wp-seo-next')];
        }

        $serverUrl = trim((string) $this->settings->get('licensing.server_url', ''));
        if ($serverUrl === '') {
            return ['ok' => false, 'status' => 400, 'error' => __('License server URL is not configured.', 'wp-seo-next')];
        }

        $path = trim((string) $this->settings->get('licensing.verify_path', '/wp-seo-next/license/verify'));
        if ($path === '') {
            $path = '/wp-seo-next/license/verify';
        }

        $endpoint = rtrim($serverUrl, '/') . '/' . ltrim($path, '/');
        $payload = $this->contract->buildPayload('verify', [
            'license_key' => $licenseKey,
        ]);

        $args = [
            'timeout' => 15,
            'headers' => $this->contract->buildHeaders('licensing', 'verify', $payload),
            'body' => $this->contract->jsonEncode($payload),
        ];

        $res = HttpClient::post($endpoint, $args, [
            'service' => 'licensing',
            'context' => 'verify',
            'retries' => 1,
            'retry_statuses' => [429, 500, 502, 503, 504],
        ]);
        if (is_wp_error($res)) {
            $retryAfter = 0;
            $data = $res->get_error_data();
            if (is_array($data) && isset($data['retry_after'])) {
                $retryAfter = (int) $data['retry_after'];
            }
            return ['ok' => false, 'status' => 0, 'error' => $res->get_error_message(), 'retry_after' => $retryAfter];
        }

        $code = (int) wp_remote_retrieve_response_code($res);
        $body = (string) wp_remote_retrieve_body($res);
        $retryAfter = $this->retryAfterFromResponse($res);
        $decoded = $body !== '' ? json_decode($body, true) : null;

        if (!is_array($decoded)) {
            $msg = $body !== '' ? $body : __('Invalid response from license server.', 'wp-seo-next');
            return ['ok' => false, 'status' => $code, 'error' => $msg, 'retry_after' => $retryAfter];
        }

        $meta = $this->augmentMeta(ServerContract::extractResponseMeta($decoded), $res);
        $connection = ServerContract::extractConnection($decoded);
        $kid = isset($meta['kid']) ? (string) $meta['kid'] : '';

        $ok = !empty($decoded['ok']);
        if (!$ok) {
            $err = isset($decoded['error']) ? (string) $decoded['error'] : __('License verification failed.', 'wp-seo-next');
            return [
                'ok' => false,
                'status' => $code,
                'error' => $err,
                'retry_after' => $retryAfter,
                'raw' => $decoded,
                'meta' => $meta,
                'connection' => $connection,
                'kid' => $kid,
            ];
        }

        $license = isset($decoded['license']) && is_array($decoded['license']) ? $decoded['license'] : [];
        $sig = isset($decoded['signature']) ? (string) $decoded['signature'] : '';
        $alg = isset($decoded['alg']) ? (string) $decoded['alg'] : '';

        return [
            'ok' => true,
            'status' => $code,
            'license' => $license,
            'signature' => $sig,
            'alg' => $alg,
            'raw' => $decoded,
            'meta' => $meta,
            'connection' => $connection,
            'kid' => $kid,
        ];
    }

    private function retryAfterFromResponse($res): int
    {
        $hdr = wp_remote_retrieve_header($res, 'retry-after');
        if (is_string($hdr) && $hdr !== '' && is_numeric($hdr)) {
            return (int) $hdr;
        }

        return 0;
    }

    /**
     * @param array<string,string> $meta
     * @return array<string,string>
     */
    private function augmentMeta(array $meta, $res): array
    {
        $map = [
            'kid' => ['x-wpsn-key-id', 'x-wpsn-kid'],
            'trace_id' => ['x-wpsn-trace-id'],
            'request_id' => ['x-wpsn-request-id'],
            'contract_version' => ['x-wpsn-contract-version'],
            'server_time' => ['date', 'x-wpsn-server-time'],
        ];

        foreach ($map as $target => $headers) {
            if (!empty($meta[$target])) {
                continue;
            }
            foreach ($headers as $header) {
                $value = wp_remote_retrieve_header($res, $header);
                if (!is_scalar($value)) {
                    continue;
                }
                $value = trim((string) $value);
                if ($value !== '') {
                    $meta[$target] = substr($value, 0, 190);
                    break;
                }
            }
        }

        return $meta;
    }
}
