<?php

namespace WPSN\Modules\Licensing;

defined('ABSPATH') || exit;

final class BillingSyncCacheRepository
{
    public const OPTION_NAME = 'wpsn_billing_center_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);
        if (!is_array($decoded)) {
            return null;
        }

        return $decoded;
    }

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

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

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