<?php

namespace App\Console\Commands;

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

class BackfillOdometerValues extends Command
{
    protected $signature = 'vehicles:backfill-odometer';

    protected $description = 'Populate missing odometer_mi or odometer_km by converting from the other';

    public function handle(): int
    {
        $converter = new Vehicle();
        $miUpdated = 0;
        $kmUpdated = 0;

        Vehicle::query()
            ->whereNotNull('odometer_km')
            ->whereNull('odometer_mi')
            ->where('odometer_km', '>', 0)
            ->eachById(function (Vehicle $vehicle) use ($converter, &$miUpdated) {
                $vehicle->update([
                    'odometer_mi' => $converter->kmToMiles($vehicle->odometer_km),
                ]);
                $miUpdated++;
            });

        Vehicle::query()
            ->whereNotNull('odometer_mi')
            ->whereNull('odometer_km')
            ->where('odometer_mi', '>', 0)
            ->eachById(function (Vehicle $vehicle) use ($converter, &$kmUpdated) {
                $vehicle->update([
                    'odometer_km' => $converter->milesToKm($vehicle->odometer_mi),
                ]);
                $kmUpdated++;
            });

        $this->info("Backfill complete. Updated {$miUpdated} missing odometer_mi, {$kmUpdated} missing odometer_km.");

        return Command::SUCCESS;
    }
}
