<?php

namespace App\Console\Commands;

use App\Jobs\RemoveOrphanedTaxonomiesFromModelsJob;
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()
    {
        $orphaned_maps = TaxonomyMap::whereDoesntHaveMorph('taxonomy', '*')->get();

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

        TaxonomyMap::whereDoesntHaveMorph('taxonomy', '*')->delete();

        $this->info("Successfully removed {$orphaned_maps->count()} orphaned taxonomy maps.");

        return 0;
    }
}
