<?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 Illuminate\Support\Str;
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) {
                        $slug = $vehicle->slug = $repository->buildSlug($vehicle);
                        // Protection for title/reg-make-model flows where data is missing to use uuid
                        if (empty(trim($slug, '-')) && !empty($vehicle->uuid)) {
                            $slug = $repository->buildSlug($vehicle, 'uuid');
                        }
                        $suffixLength = $repository->slugSuffixLength();
                        while (Vehicle::query()
                            ->where('slug', $vehicle->slug)
                            ->when($vehicle->exists, fn ($q) => $q->whereKeyNot($vehicle->getKey()))
                            ->exists()
                        ) {
                            $vehicle->slug = $slug . '-' . strtolower(Str::random($suffixLength));
                        }
                        $vehicle->save();
                    });
                }
            );

        return 0;
    }
}
