<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;

final class ExculCacheService
{
    private const STAT_KEY = 'excul:stats';
    private const STAT_TTL = 60;
    private const LIST_TTL = 30;

    public function getStats(callable $loader): array
    {
        return Cache::remember(self::STAT_KEY, self::STAT_TTL, $loader);
    }

    public function getList(string $key, callable $loader): mixed
    {
        if ($this->supportsTag()) {
            return Cache::tags(['excul:list'])->remember($key, self::LIST_TTL, $loader);
        }

        return Cache::remember($key, self::LIST_TTL, $loader);
    }

    public function invalidateStats(): void
    {
        Cache::forget(self::STAT_KEY);
    }

    public function invalidateList(): void
    {
        if ($this->supportsTag()) {
            Cache::tags(['excul:list'])->flush();
            return;
        }
    }

    private function supportsTag(): bool
    {
        return in_array(config('cache.default'), ['redis', 'memcached'], true);
    }
}