<?php

declare(strict_types=1);


namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Setting extends Model
{
    protected $primaryKey = 'key';

    public $incrementing = false;

    protected $keyType = 'string';

    protected $fillable = ['key', 'value'];

    public const CACHE_KEY = 'blog.settings';

    public static function get(string $key, mixed $default = null): mixed
    {
        $settings = self::allSettings();

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

    public static function set(string $key, mixed $value): void
    {
        self::updateOrCreate(['key' => $key], ['value' => is_scalar($value) || $value === null ? $value : json_encode($value)]);
        self::flushCache();
    }

    public static function forget(string $key): void
    {
        self::where('key', $key)->delete();
        self::flushCache();
    }

    public static function allSettings(): array
    {
        return Cache::remember(self::CACHE_KEY, now()->addDay(), function () {
            return self::query()->pluck('value', 'key')->all();
        });
    }

    public static function flushCache(): void
    {
        Cache::forget(self::CACHE_KEY);
    }

    public static function seedDefaults(array $defaults): void
    {
        foreach ($defaults as $key => $value) {
            if (! self::query()->where('key', $key)->exists()) {
                self::query()->create(['key' => $key, 'value' => $value]);
            }
        }
        self::flushCache();
    }
}
