<?php

namespace App\Services\System;

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

class SettingsService
{
    private const CACHE_KEY = 'dw_settings_all';

    private const CACHE_TTL = 30;

    /**
     * @return array<string,mixed>
     */
    public function all(): array
    {
        return Cache::remember(self::CACHE_KEY, self::CACHE_TTL, function (): array {
            $out = [];
            foreach (Setting::all(['key', 'value']) as $setting) {
                $out[$setting->key] = $setting->value;
            }

            return $out;
        });
    }

    public function get(string $key, mixed $default = null): mixed
    {
        $all = $this->all();

        return array_key_exists($key, $all) ? $all[$key] : $default;
    }

    /**
     * @param  array<string,mixed>  $values
     */
    public function setMany(array $values, ?string $updatedBy = null): void
    {
        foreach ($values as $key => $value) {
            Setting::updateOrCreate(
                ['key' => (string) $key],
                ['value' => $value, 'updated_by' => $updatedBy]
            );
        }
        Cache::forget(self::CACHE_KEY);
    }
}
