<?php

namespace App\Console\Commands;

use App\Jobs\RemoveOrphanedTaxonomiesFromModelsJob;
use App\Master\Models\BodyStyleType;
use App\Master\Models\DrivetrainType;
use App\Master\Models\FuelType;
use App\Master\Models\TransmissionType;
use App\Master\Models\VehicleMake;
use App\Master\Models\VehicleModel;
use App\TaxonomyMap;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;

class RemoveOrphanedTaxonomyMaps extends Command
{
    use DispatchesJobs;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'taxonomy:cleanup';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove all taxonomy maps that are missing a corresponding taxonomy';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $morphTypes = [
            VehicleMake::class,
            VehicleModel::class,
            FuelType::class,
            TransmissionType::class,
            BodyStyleType::class,
            DrivetrainType::class,
        ];

        $orphaned_maps = TaxonomyMap::whereDoesntHaveMorph('taxonomy', $morphTypes)->get();

        $this->dispatch(new RemoveOrphanedTaxonomiesFromModelsJob($orphaned_maps));

        $this->info("Dispatched cleanup for {$orphaned_maps->count()} orphaned taxonomy maps.");

        return 0;
    }
}
