<?php

namespace App\Console\Commands;

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

class FixSettings extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fix:settings';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix settings order and remove obsolete settings';

    /**
     * Add config_keys here to remove them from all tenants.
     */
    private const OBSOLETE_SETTINGS = [
        'stock-skupenet-partner-id',
        'stock-skupenet-password',
    ];

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->fixEnabledSettingsOrder();
        $this->removeObsoleteSettings();
    }

    private function fixEnabledSettingsOrder(): void
    {
        Setting::query()
            ->where('name', 'Enabled')
            ->where('type', 'boolean')
            ->update(['order' => 0]);

        Setting::query()
            ->where('name', '<>', 'Enabled')
            ->where('order', 0)
            ->update(['order' => 1]);
    }

    private function removeObsoleteSettings(): void
    {
        if (empty(self::OBSOLETE_SETTINGS)) {
            return;
        }

        $deleted = Setting::query()
            ->whereIn('config_key', self::OBSOLETE_SETTINGS)
            ->delete();

        $this->info("Deleted {$deleted} obsolete setting(s).");
    }
}
