<?php

namespace App\Services;

use App\Models\Setting;
use Illuminate\Support\Facades\Schema;

class SettingsService
{
    public function get(string $group, string $key, mixed $default = null): mixed
    {
        if (! Schema::hasTable('settings')) {
            return $default;
        }

        $setting = Setting::where('group', $group)->where('key', $key)->first();

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

    public function group(string $group, array $defaults = []): array
    {
        if (! Schema::hasTable('settings')) {
            return $defaults;
        }

        $values = Setting::where('group', $group)->pluck('value', 'key')->all();

        return array_replace_recursive($defaults, $values);
    }

    public function put(string $group, string $key, mixed $value, string $type = 'json', bool $public = false): Setting
    {
        return Setting::updateOrCreate(
            ['group' => $group, 'key' => $key],
            ['value' => $value, 'type' => $type, 'is_public' => $public]
        );
    }
}
