<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Mtc\MercuryDataModels\VehicleAttributeValue;
use Mtc\MercuryDataModels\VehicleAutoTraderData;
use Mtc\MercuryDataModels\VehicleFeature;
use Mtc\MercuryDataModels\VehicleFinance;
use Mtc\MercuryDataModels\VehicleLabel;
use Mtc\MercuryDataModels\VehicleStandardEquipment;
use Mtc\MercuryDataModels\VehicleTechnicalData;
use Mtc\MercuryDataModels\VehicleView;

class RemoveOrphanedVehicleData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'vehicles:purge-orphaned-data';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove vehicle data for hard deleted vehicles';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $limit = 5000;

        collect([
            VehicleAutoTraderData::class,
            VehicleFinance::class,
            VehicleLabel::class,
            VehicleView::class,
        ])->each(fn ($model_name) => $this->deleteOrphanedRows($model_name, $limit));

        collect([
            VehicleAttributeValue::class,
            VehicleStandardEquipment::class,
            VehicleTechnicalData::class,
            VehicleFeature::class,
        ])->each(fn ($model_name) => $this->deleteOrphanedRows($model_name, $limit, 'owner'));
    }

    private function deleteOrphanedRows(string $model_name, int $limit, string $relation = 'vehicle')
    {
        $model_name::query()
            ->whereDoesntHave($relation, function ($query) {
                return $query->withTrashed();
            })
            ->limit($limit)
            ->delete();
    }
}
