<?php

namespace WPSN\Modules\Licensing;

defined('ABSPATH') || exit;

final class SelfServeUpgradeCacheRepository
{
    public const OPTION_NAME = 'wpsn_self_serve_upgrade_cache';

    /**
     * @return array<string,mixed>|null
     */
    public function get(): ?array
    {
        $raw = get_option(self::OPTION_NAME);
        if (!is_string($raw) || $raw === '') {
            return null;
        }

        $json = LicenseCrypto::decrypt($raw);
        if ($json === '') {
            return null;
        }

        $decoded = json_decode($json, true);
        return is_array($decoded) ? $decoded : null;
    }

    /**
     * @param array<string,mixed> $data
     */
    public function set(array $data): void
    {
        $json = wp_json_encode($data);
        if (!is_string($json) || $json === '') {
            return;
        }

        update_option(self::OPTION_NAME, LicenseCrypto::encrypt($json), false);
    }

    public function clear(): void
    {
        delete_option(self::OPTION_NAME);
    }
}
