<?php

namespace App\Nexus\Engine;

use App\Nexus\Models\NexusConfig as NexusConfigModel;

/**
 * NEXUS ENGINE - NexusConfig (Engine Helper)
 *
 * Thin wrapper over the deployed NexusConfig model.
 * The model handles caching (Laravel Cache, 5-min TTL) and type casting.
 *
 * Deployed model uses columns: key, value, type, group, is_editable
 * Deployed model provides: get(), set(), isEngineActive(), isEnginePaused()
 *
 * @package App\Nexus\Engine
 */
class NexusConfig
{
    public static function get(string $key, $default = null)
    {
        return NexusConfigModel::get($key, $default);
    }

    public static function getFloat(string $key, float $default = 0.0): float
    {
        $value = self::get($key);
        return $value !== null ? (float) $value : $default;
    }

    public static function getInt(string $key, int $default = 0): int
    {
        $value = self::get($key);
        return $value !== null ? (int) $value : $default;
    }

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

    public static function set(string $key, string $value, ?int $adminId = null): void
    {
        $oldValue = self::get($key);
        NexusConfigModel::set($key, $value);

        NexusAuditLogger::logAdminAction(
            $adminId ?? 0,
            'config_changed',
            'config',
            null,
            "Changed {$key}: {$oldValue} -> {$value}",
            ['key' => $key, 'old_value' => $oldValue, 'new_value' => $value]
        );
    }

    public static function getGroup(string $group): array
    {
        return NexusConfigModel::getGroup($group);
    }

    public static function isNexusActive(): bool
    {
        return NexusConfigModel::isEngineActive();
    }

    public static function isEmergencyPaused(): bool
    {
        return NexusConfigModel::isEnginePaused();
    }

    public static function isOperational(): bool
    {
        return self::isNexusActive() && !self::isEmergencyPaused();
    }

    public static function refresh(): void
    {
        try {
            $rows = NexusConfigModel::all(['key']);
            foreach ($rows as $row) {
                \Illuminate\Support\Facades\Cache::forget('nexus_config_' . $row->key);
            }
        } catch (\Exception $e) {
            \Log::error('NexusConfig::refresh failed', ['error' => $e->getMessage()]);
        }
    }
}
