<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Mtc\MercuryDataModels\Setting;

class EnsureSettingsHaveSources extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'settings:ensure-setting-sources';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Ensure that settings have expected sources. Repairs mis-seeded settings.';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $setting_sources = [
            'app-content-blog-default-template' => 'templates',
            'app-content-news-default-template' => 'templates',
            'app-content-reviews-default-template' => 'templates',
            'app-content-guides-default-template' => 'templates',
            'app-content-events-default-template' => 'templates',
            'app-details-country' => 'countries',
            'app-details-currency' => 'currencies',
        ];

        collect($setting_sources)->each(function ($source, $config_key) {
            $setting = Setting::query()
                ->where('config_key', $config_key)
                ->whereNull('source')
                ->first();

            if ($setting) {
                if ($setting->type == 'text') {
                    $setting->type = 'string';
                    $setting->value = $setting->value_text;
                }

                $setting->source = $source;
                $setting->save();
            }
        });
    }
}
