<?php

declare(strict_types=1);

namespace Numinix\SeekmodoSdk\Search;

use Numinix\SeekmodoSdk\Storage\CacheInterface;

/**
 * Parses and stores the gateway `fallback_bundle` from tenant.snapshot.
 */
final class FallbackBundle
{
    public const CACHE_KEY = 'numinix.seekmodo.fallback_bundle';
    public const EXTENDED_TTL = 86400;

    private CacheInterface $cache;

    public function __construct(CacheInterface $cache)
    {
        $this->cache = $cache;
    }

    /**
     * @param array<string,mixed> $snapshot
     */
    public function ingestFromSnapshot(array $snapshot): void
    {
        $bundle = $snapshot['fallback_bundle'] ?? null;
        if (!is_array($bundle)) {
            return;
        }
        $this->cache->set(self::CACHE_KEY, $this->normalizeBundle($bundle), self::EXTENDED_TTL);
    }

    /**
     * @return array{version: int, synonyms: array, pins: array, rescue: array, bestsellers: array}
     */
    public function get(): array
    {
        $cached = $this->cache->get(self::CACHE_KEY);
        if (!is_array($cached)) {
            return $this->empty();
        }

        return $this->normalizeBundle($cached);
    }

    public function forget(): void
    {
        $this->cache->delete(self::CACHE_KEY);
    }

    /**
     * @return array{version: int, synonyms: array, pins: array, rescue: array, bestsellers: array}
     */
    public function empty(): array
    {
        return [
            'version' => 1,
            'synonyms' => [],
            'pins' => [],
            'rescue' => [],
            'bestsellers' => [],
        ];
    }

    /**
     * @param array<string,mixed> $bundle
     * @return array{version: int, synonyms: array, pins: array, rescue: array, bestsellers: array}
     */
    private function normalizeBundle(array $bundle): array
    {
        return [
            'version' => (int) ($bundle['version'] ?? 1),
            'synonyms' => is_array($bundle['synonyms'] ?? null) ? $bundle['synonyms'] : [],
            'pins' => is_array($bundle['pins'] ?? null) ? $bundle['pins'] : [],
            'rescue' => is_array($bundle['rescue'] ?? null) ? $bundle['rescue'] : [],
            'bestsellers' => is_array($bundle['bestsellers'] ?? null) ? $bundle['bestsellers'] : [],
        ];
    }
}
