<?php

declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Mtc\MercuryDataModels\Setting;

class RenameAutoTraderToAutotraderInSettings extends Command
{
    /**
     * @var string
     */
    protected $signature = 'autonomy:rename-autotrader-settings';

    /**
     * @var string
     */
    protected $description = 'Rewrite the brand "AutoTrader" to "Autotrader" in the four '
        . 'user-visible columns of the settings table. Safe to re-run.';

    public function handle(): int
    {
        $affected = Setting::query()
            ->where(function ($query) {
                $query->where('name', 'like', '%AutoTrader%')
                    ->orWhere('description', 'like', '%AutoTrader%')
                    ->orWhere('section', 'like', '%AutoTrader%')
                    ->orWhere('group', 'like', '%AutoTrader%');
            })
            ->update([
                'name' => DB::raw("REPLACE(name, 'AutoTrader', 'Autotrader')"),
                'description' => DB::raw("REPLACE(description, 'AutoTrader', 'Autotrader')"),
                'section' => DB::raw("REPLACE(section, 'AutoTrader', 'Autotrader')"),
                'group' => DB::raw("REPLACE(`group`, 'AutoTrader', 'Autotrader')"),
            ]);

        $this->info("Rebranded {$affected} setting row(s).");

        return self::SUCCESS;
    }
}
