<?php

namespace App\Models;

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

class Configuracion extends Model
{
    use HasFactory;

    protected $table = 'configuraciones';

    protected $fillable = ['clave', 'valor', 'tipo', 'grupo', 'etiqueta', 'descripcion'];

    public static function obtener(string $clave, mixed $defecto = null): mixed
    {
        $todas = Cache::remember('configuraciones.todas', 600, fn () => static::pluck('valor', 'clave')->toArray());
        return $todas[$clave] ?? $defecto;
    }

    public static function definir(string $clave, mixed $valor): void
    {
        static::where('clave', $clave)->update(['valor' => $valor]);
        Cache::forget('configuraciones.todas');
    }

    public static function limpiarCache(): void
    {
        Cache::forget('configuraciones.todas');
    }

    protected static function booted(): void
    {
        static::saved(fn () => static::limpiarCache());
        static::deleted(fn () => static::limpiarCache());
    }
}
