<?php

namespace App\Models;

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

class AppSetting extends Model
{
    protected $fillable = ['key','value','type','group'];

    public static function allCached(): array
    {
        return Cache::rememberForever('app_settings', function () {
            return self::query()->get(['key','value','type'])->mapWithKeys(function ($row) {
                return [$row->key => self::castOut($row->value, $row->type)];
            })->toArray();
        });
    }

    public static function get(string $key, $default = null)
    {
        $all = self::allCached();
        return array_key_exists($key, $all) ? $all[$key] : $default;
    }

    public static function getInt(string $key, int $default): int
    {
        return (int) self::get($key, $default);
    }

    public static function getBool(string $key, bool $default): bool
    {
        $v = self::get($key, $default);
        if (is_bool($v)) return $v;
        return in_array(strtolower((string)$v), ['1','true','yes','on'], true);
    }

    public static function setValue(string $key, $value, string $type = 'string'): void
    {
        $stored = self::castIn($value, $type);
        $row = self::updateOrCreate(['key'=>$key], ['value'=>$stored, 'type'=>$type]);
        Cache::forget('app_settings');
    }

    private static function castOut($value, string $type)
    {
        return match ($type) {
            'int'  => (int)$value,
            'bool' => in_array(strtolower((string)$value), ['1','true','yes','on'], true),
            'json' => json_decode((string)$value, true),
            default => $value,
        };
    }

    private static function castIn($value, string $type)
    {
        return match ($type) {
            'json' => json_encode($value),
            default => (string)$value,
        };
    }
}
