<?php

namespace App\Models;

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

class Setting extends Model
{
    protected $guarded = [];

    protected static function booted(): void
    {
        static::saved(fn () => Cache::forget('app.settings'));
        static::deleted(fn () => Cache::forget('app.settings'));
    }

    /** All settings as a decoded key => value map (cached). Safe before the table exists. */
    public static function map(): array
    {
        if (! Schema::hasTable('settings')) {
            return [];
        }

        return Cache::rememberForever('app.settings', function () {
            return static::query()->get()->mapWithKeys(function (self $s) {
                $value = $s->value;

                if ($s->encrypted && $value !== null && $value !== '') {
                    try {
                        $value = Crypt::decryptString($value);
                    } catch (\Throwable $e) {
                        $value = null;
                    }
                }

                return [$s->key => $value];
            })->all();
        });
    }

    public static function get(string $key, mixed $default = null): mixed
    {
        return static::map()[$key] ?? $default;
    }

    public static function put(string $key, mixed $value, bool $encrypt = false): void
    {
        $stored = ($encrypt && $value !== null && $value !== '')
            ? Crypt::encryptString((string) $value)
            : $value;

        static::updateOrCreate(['key' => $key], ['value' => $stored, 'encrypted' => $encrypt]);
    }
}
