<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Setting;
use Illuminate\Support\Facades\Cache;

final class SettingService
{
    private const CACHE_KEY = 'settings.all';
    private const CACHE_TTL = 86400; // 24 hours

    /**
     * Get all settings as an associative array.
     *
     * @return array<string, string|null>
     */
    public function all(): array
    {
        try {
            return Cache::remember(self::CACHE_KEY, self::CACHE_TTL, function () {
                return Setting::pluck('value', 'key')->all();
            });
        } catch (\Throwable) {
            return [];
        }
    }

    /**
     * Get a setting value by key.
     */
    public function get(string $key, ?string $default = null): ?string
    {
        $settings = $this->all();

        return $settings[$key] ?? $default;
    }

    /**
     * Set a setting value.
     */
    public function set(string $key, ?string $value): void
    {
        Setting::updateOrCreate(
            ['key' => $key],
            ['value' => $value]
        );

        $this->clearCache();
    }

    /**
     * Set multiple settings at once.
     *
     * @param array<string, string|null> $settings
     */
    public function setMany(array $settings): void
    {
        foreach ($settings as $key => $value) {
            Setting::updateOrCreate(
                ['key' => $key],
                ['value' => $value]
            );
        }

        $this->clearCache();
    }

    /**
     * Clear settings cache.
     */
    public function clearCache(): void
    {
        Cache::forget(self::CACHE_KEY);
    }
}
