<?php

namespace ILC\ConfigCenter\Models;

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

class Configuracion extends Model
{
    use HasFactory;

	protected $fillable = [
        'nombre',
        'identificador',
        'descripcion',
        'tipo',
        'opciones',
        'valor',
        'tags'
    ];

    protected $casts = [
        'updated_at' => 'datetime:d-m-Y H:i'
    ];

    public function valor(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => json_decode($value),
            set: fn (Mixed $value) => json_encode($value)
        );
    }

    public function __construct(array $attributes = [])
    {
        $this->table = config('configcenter.tabla','configuraciones');
    }

	public static function cargarCache()
    {
        $settings = Cache::get('db_setting', null);
		if(is_null($settings)){
			$settings = self::refrescarCache();
		}
        return $settings;
    }

    public static function refrescarCache()
    {
        Cache::forget('db_setting');
        Cache::rememberForever(
			'db_setting',
			fn() => static::query()->get()->toBase()->flatmap(fn($configuracion) => [$configuracion->identificador => $configuracion->valor])
		);

        return self::cargarCache();
    }
}
