<?php

namespace App\Models;

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

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

    /**
     * Get the cache key for a given setting key.
     */
    protected static function cacheKey(string $key): string
    {
        return 'setting_' . $key;
    }

    /**
     * Get a setting value by key, using cache (10 min TTL).
     * Uses the default CACHE_STORE — array in tests, file/database in production.
     */
    public static function getValue(string $key, $default = null)
    {
        try {
            return Cache::remember(
                static::cacheKey($key),
                600,
                function () use ($key, $default) {
                    try {
                        $setting = self::where('key', $key)->first();
                        if (!$setting) {
                            return $default;
                        }
                        $val = $setting->value;
                        if (is_string($val) && (str_starts_with($val, '[') || str_starts_with($val, '{'))) {
                            $decoded = json_decode($val, true);
                            if (json_last_error() === JSON_ERROR_NONE) {
                                return $decoded;
                            }
                        }
                        return $val;
                    } catch (\Throwable $dbEx) {
                        return $default;
                    }
                }
            );
        } catch (\Throwable $cacheEx) {
            return $default;
        }
    }

    /**
     * Set/update a setting value and clear its cache entry.
     */
    public static function setValue(string $key, $value, string $group = 'general'): self
    {
        if (is_array($value)) {
            $value = json_encode($value, JSON_UNESCAPED_UNICODE);
        }

        $record = self::updateOrCreate(
            ['key' => $key],
            ['value' => $value, 'group' => $group]
        );

        static::clearCache($key);

        return $record;
    }

    /**
     * Clear the cache for a specific setting key, or all settings if null.
     */
    public static function clearCache(?string $key = null): void
    {
        Cache::forget('site_settings_compiled');
        if ($key !== null) {
            Cache::forget(static::cacheKey($key));
        } else {
            Cache::flush();
        }
    }
}
