<?php

namespace App\Setting;

use Illuminate\Routing\Router;
use Illuminate\Support\Collection;

class SettingFactory
{
    /**
     * @var array<int, class-string<LocalSettings>>
     */
    private array $settings = [];

    /**
     * @param class-string<LocalSettings> $setting
     */
    public function register(string $setting): void
    {
        $this->settings[] = $setting;

        if (1 === count($this->settings)) {
            app(Router::class)->redirect('/setting', '/setting/' . $setting::group());
        }
    }

    /**
     * @return Collection<int, LocalSettings>
     */
    public function all(): Collection
    {
        return collect($this->settings)->map(fn ($setting) => new $setting);
    }

    public function resolveGroupName(string $name): LocalSettings
    {
        $settingClass = collect($this->settings)->first(fn ($setting) => $setting::group() === $name);

        return app($settingClass);
    }
}
