<?php

namespace App\Console\Commands;

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

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix order for vehicles - replacing null with actual order value';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $currentMaxOrder = Vehicle::max('order') ?? 0;

        $vehiclesToFix = Vehicle::query()
            ->whereNull('order')
            ->orderBy('id', 'asc')
            ->get();

        $newOrder = $currentMaxOrder + 1;

        foreach ($vehiclesToFix as $vehicle) {
            $vehicle->order = $newOrder++;
            $vehicle->save();
        }

        $this->info(count($vehiclesToFix) . ' vehicles updated with new order values.');
    }
}
