<?php

namespace App\Modules\Admin\Tenancy\Services;

use App\Modules\Admin\Tenancy\Models\Module;
use App\Modules\Admin\Tenancy\Repositories\ModuleRepository;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Cache;

class ModuleRegistryService
{
    private const CACHE_TTL_SECONDS = 600;

    public function __construct(
        private readonly ModuleRepository $modules,
    ) {}

    /**
     * @return Collection<int, Module>
     */
    public function activeModules(): Collection
    {
        return Cache::remember(
            $this->cacheKey('active'),
            self::CACHE_TTL_SECONDS,
            fn (): Collection => $this->modules->allActiveOrdered(),
        );
    }

    public function activeBySlug(string $slug): ?Module
    {
        return $this->activeModules()->firstWhere('slug', $slug);
    }

    public function forget(): void
    {
        Cache::forget($this->cacheKey('active'));
    }

    private function cacheKey(string $suffix): string
    {
        return 'module_registry:'.$suffix;
    }
}

