<?php

namespace App\Models;

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

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

    protected $casts = [
        'value' => 'array',
    ];

    public static function getValue(string $key, mixed $default = null): mixed
    {
        if (! Schema::hasTable('stage_academy_settings')) {
            return $default;
        }

        $record = static::query()->where('key', $key)->first();

        return $record?->value ?? $default;
    }

    public static function setValue(string $key, mixed $value): void
    {
        if (! Schema::hasTable('stage_academy_settings')) {
            return;
        }

        static::query()->updateOrCreate(
            ['key' => $key],
            ['value' => $value]
        );
    }

    public static function getMany(array $keys): array
    {
        if (! Schema::hasTable('stage_academy_settings')) {
            $result = [];
            foreach ($keys as $key) {
                $result[$key] = null;
            }

            return $result;
        }

        $records = static::query()
            ->whereIn('key', $keys)
            ->get()
            ->keyBy('key');

        $result = [];
        foreach ($keys as $key) {
            $result[$key] = $records[$key]->value ?? null;
        }

        return $result;
    }
}
