<?php

namespace App\Console\Commands;

use App\Facades\Settings;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\Vehicle;

class SetMissingVehicleTitles extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'vehicles:set-missing-titles';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Set titles for vehicles without titles';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        if (!Settings::get('auto-update-vehicle-title')) {
            $this->info('Setting "auto-update-vehicle-title" is disabled. Cannot update vehicle titles.');
            return;
        }

        Vehicle::query()
            ->where(fn($query) => $query->whereNull('title')->orWhere('title', ' '))
            ->whereNotNull('make_id')
            ->whereNotNull('model_id')
            ->chunkById(
                100,
                function (Collection $chunk) {
                    $chunk->each(function ($vehicle) {
                        try {
                            $vehicle->title = $vehicle->make?->name . ' ' . $vehicle->model?->name;
                            $vehicle->save();
                        } catch (\Throwable $exception) {
                            Log::error('Exception: ' . $exception->getMessage());
                        }
                    });
                }
            );
    }
}
