<?php

declare(strict_types=1);

namespace Numinix\SeekmodoSdk\Search;

use Numinix\SeekmodoSdk\Storage\CacheInterface;

/**
 * Last-known-good ranked ID cache for brief gateway outages.
 */
final class LkgCache
{
    private const PREFIX = 'numinix.seekmodo.lkg.';
    private const DEFAULT_TTL = 3600;

    private CacheInterface $cache;
    private int $ttlSeconds;

    public function __construct(CacheInterface $cache, int $ttlSeconds = self::DEFAULT_TTL)
    {
        $this->cache = $cache;
        $this->ttlSeconds = $ttlSeconds;
    }

    /**
     * @param list<int> $ids
     */
    public function store(string $normalizedQ, array $ids): void
    {
        if ($normalizedQ === '' || $ids === []) {
            return;
        }
        $this->cache->set(self::PREFIX . $normalizedQ, array_values($ids), $this->ttlSeconds);
    }

    /**
     * @return list<int>|null
     */
    public function get(string $normalizedQ): ?array
    {
        if ($normalizedQ === '') {
            return null;
        }
        $v = $this->cache->get(self::PREFIX . $normalizedQ);
        if (!is_array($v)) {
            return null;
        }
        $out = [];
        foreach ($v as $id) {
            $n = (int) $id;
            if ($n > 0) {
                $out[] = $n;
            }
        }

        return $out === [] ? null : $out;
    }
}
