<?php

namespace Database\Seeders\Tenant;

use App\Facades\Settings;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Cache;
use Mtc\MercuryDataModels\Setting;

class SettingsDefinitionSeeder extends Seeder
{
    public function run(?array $settings = null): void
    {
        $settings ??= require base_path('database/seeders/data/settings.php');

        $configKeys = [];

        foreach ($settings as $setting) {
            foreach ($setting as $key => $val) {
                if ($val instanceof \Closure) {
                    $setting[$key] = $val();
                }
            }

            Settings::make($setting);
            $configKeys[] = $setting['config_key'];
        }

        Setting::query()
            ->whereNotIn('config_key', $configKeys)
            ->where('tab', '!=', '')
            ->delete();

        Cache::forget(tenant('id') . '-settings');
    }
}
