<?php

namespace App\Models;

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Eloquent\Model;
use Throwable;

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

    /**
     * Read one setting value with optional fallback.
     */
    public static function getValue(string $key, ?string $default = null): ?string
    {
        try {
            if (! Schema::hasTable('app_settings')) {
                return $default;
            }
            $setting = static::query()->where('key', $key)->first();

            return $setting?->value ?? $default;
        } catch (Throwable) {
            return $default;
        }
    }

    /**
     * Create or update a setting value by key.
     */
    public static function setValue(string $key, ?string $value): void
    {
        try {
            if (! Schema::hasTable('app_settings')) {
                return;
            }
            static::query()->updateOrCreate(
                ['key' => $key],
                ['value' => $value]
            );
        } catch (Throwable) {
            // Avoid breaking requests when migration is missing on a deployed environment.
            return;
        }
    }
}
