<?php

namespace FluxCms\Core\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;

/**
 * Liefert die Namen der Outline-Heroicons (Präfix o- im Paket) für dynamische Auswahl.
 * Ergebnis wird über den Flux-CMS-Cache gebündelt, damit das SVG-Verzeichnis nicht bei jedem Request gescannt wird.
 */
final class HeroiconOutlineList
{
    /**
     * @return array<int, string>
     */
    public static function names(): array
    {
        if (! config('flux-cms.cache.enabled', true)) {
            return self::scanFilesystem();
        }

        $prefix = config('flux-cms.cache.key_prefix', 'flux_cms');
        $ttl = (int) config('flux-cms.cache.ttl', 3600);
        $key = "{$prefix}.heroicon_outline_names";
        $store = config('flux-cms.cache.store');

        $callback = fn (): array => self::scanFilesystem();

        if ($store) {
            return Cache::store($store)->remember($key, $ttl, $callback);
        }

        return Cache::remember($key, $ttl, $callback);
    }

    public static function forgetCached(): void
    {
        $prefix = config('flux-cms.cache.key_prefix', 'flux_cms');
        $key = "{$prefix}.heroicon_outline_names";
        $store = config('flux-cms.cache.store');

        if ($store) {
            Cache::store($store)->forget($key);

            return;
        }

        Cache::forget($key);
    }

    /**
     * @return array<int, string>
     */
    public static function scanFilesystem(): array
    {
        $path = base_path('vendor/blade-ui-kit/blade-heroicons/resources/svg');
        if (! File::isDirectory($path)) {
            return [];
        }

        return collect(File::files($path))
            ->map(fn (\SplFileInfo $file): string => $file->getFilenameWithoutExtension())
            ->filter(fn (string $name): bool => str_starts_with($name, 'o-'))
            ->map(fn (string $name): string => substr($name, 2))
            ->sort()
            ->values()
            ->toArray();
    }
}
