<?php

declare (strict_types=1);
namespace DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout;

use WP_REST_Request;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout\Violations\CheckoutError;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Enums\UcpVersion;
/**
 * Validates UCP required headers.
 */
final class HeaderValidator
{
    /**
     * Validate required UCP headers.
     */
    public function validate(WP_REST_Request $request): ?CheckoutError
    {
        $ucp_agent = $request->get_header('ucp-agent');
        $idempotency_key = $request->get_header('idempotency-key');
        $request_signature = $request->get_header('request-signature');
        $request_id = $request->get_header('request-id');
        if (empty($ucp_agent)) {
            return CheckoutError::header_missing('UCP-Agent');
        }
        if (empty($idempotency_key) && !$request->is_method('GET')) {
            return CheckoutError::header_missing('Idempotency-Key');
        }
        if (empty($request_signature)) {
            return CheckoutError::header_missing('Request-Signature');
        }
        if (empty($request_id)) {
            return CheckoutError::header_missing('Request-Id');
        }
        return $this->validate_version($ucp_agent);
    }
    /**
     * Validate UCP-Agent version.
     */
    private function validate_version(string $ucp_agent): ?CheckoutError
    {
        $agent_version = UcpVersion::CURRENT;
        if (\preg_match('/(?:^|;)\s*version=(?:"([^"]+)"|([^;]+))/i', $ucp_agent, $matches)) {
            $agent_version = \trim($matches[1] !== '' ? $matches[1] : $matches[2]);
        }
        if ($agent_version > UcpVersion::CURRENT) {
            return CheckoutError::version_unsupported($agent_version, UcpVersion::CURRENT);
        }
        return null;
    }
}
