<?php

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

/**
 * Idempotency store backed by wp_options table.
 *
 * Each idempotency key maps to one option row with autoload=false.
 */
final class IdempotencyStore
{
    private const OPTION_PREFIX = '_ucp_idempotency_';
    /**
     * @return array{hash: string, status_code: int, response: array<string, mixed>}|null
     */
    public function get(string $idempotency_key): ?array
    {
        $option_name = $this->option_name($idempotency_key);
        $json = \get_option($option_name, null);
        if (null === $json || !\is_string($json)) {
            return null;
        }
        $data = \json_decode($json, \true);
        if (!\is_array($data)) {
            return null;
        }
        if (!isset($data['hash'], $data['status_code'], $data['response'])) {
            return null;
        }
        return ['hash' => (string) $data['hash'], 'status_code' => (int) $data['status_code'], 'response' => \is_array($data['response']) ? $data['response'] : []];
    }
    /**
     * Save a response for an idempotency key.
     *
     * @param array<string, mixed> $response Response body to replay.
     */
    public function save(string $idempotency_key, string $request_hash, int $status_code, array $response): void
    {
        $option_name = $this->option_name($idempotency_key);
        $data = ['hash' => $request_hash, 'status_code' => $status_code, 'response' => $response];
        \update_option($option_name, \wp_json_encode($data), \false);
    }
    /**
     * @param array<string, mixed> $data Request body.
     */
    public function compute_hash(array $data): string
    {
        \ksort($data);
        $encoded = \wp_json_encode($data);
        if (\false === $encoded) {
            return '';
        }
        return \hash('sha256', $encoded);
    }
    private function option_name(string $idempotency_key): string
    {
        return self::OPTION_PREFIX . \md5($idempotency_key);
    }
}
