<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Mtc\MercuryDataModels\NewCar;
use Mtc\MercuryDataModels\VehicleTrim;

class LinkTrimsToNewCars extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'new-cars:link-trims-from-make-model';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Add new_car_id for trims based on make/model ';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $all = VehicleTrim::query()
            ->whereNull('new_car_id')
            ->get();

        $progress = $this->output->createProgressBar($all->count());

        $all->each(function (VehicleTrim $trim) use ($progress) {
            $this->link($trim);
            $progress->advance();
        });
    }

    private function link(VehicleTrim $trim)
    {
        $trim->update([
            'new_car_id' => NewCar::query()
                ->where('make_id', $trim->make_id)
                ->where('model_id', $trim->model_id)
                ->first()
                ?->id,
        ]);
    }
}
