<?php

namespace App\Console\Commands;

use App\Facades\Settings;
use App\VehicleRepository;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\Vehicle;

class RecreateVehicleSlugs extends Command
{
    use DispatchesJobs;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'vehicles:recreate-slugs';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Recreate the slug for available vehicles using the url setting configured in admin';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(VehicleRepository $repository)
    {
        dump('Recreating vehicle slugs with format: ' . Settings::get('automotive-vehicles-url_building_format'));

        Vehicle::query()
            ->chunk(
                100,
                function (Collection $chunk, $index) use ($repository) {

                    dump('chunk ' . $index);

                    $chunk->each(function (Vehicle $vehicle) use ($repository) {
                        $vehicle->slug = $repository->buildSlug($vehicle);
                        $vehicle->save();
                    });
                }
            );

        return 0;
    }
}
