<?php

namespace App\Console\Commands;

use App\Facades\Settings;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Mtc\MercuryDataModels\Vehicle;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove old/archived vehicles';

    private int $defaultExpiryDays = 90;
    private int $defaultFullyPurgeDays = 1095; // 3 years

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $expiry = Settings::get('app-old-stock-expiry-days') ?: $this->defaultExpiryDays;
        $this->output->info('Removing vehicles that have been removed for X days: ' . $expiry);
        Vehicle::onlyTrashed()
            ->whereNull('purged_at')
            ->where('deleted_at', '<=', Carbon::now()->subDays($expiry))
            ->chunk(250, fn($collection) => $collection
                ->tap(fn($collection) => $this->output->info('Records to remove in batch: ' . $collection->count()))
                ->each(fn(Vehicle $vehicle) => $this->purgeNonEssentialData($vehicle)));

        $fullExpiry = Settings::get('app-old-stock-full-purge-days') ?: $this->defaultFullyPurgeDays;
        $this->output->info('Processing vehicles for full purge after days: ' . $fullExpiry);
        Vehicle::onlyTrashed()
            ->where('deleted_at', '<=', Carbon::now()->subDays($fullExpiry))
            ->chunk(250, function ($collection) {
                $this->output->info('Fully deleting batch size: ' . $collection->count());
                $collection->each(fn(Vehicle $vehicle) => $this->fullPurge($vehicle));
            });
    }

    private function purgeNonEssentialData(Vehicle $vehicle): void
    {
        $vehicle->specs()->delete();
        $vehicle->features()->delete();
        $vehicle->financeExamples()->delete();
        $vehicle->autoTraderData()->delete();
        $vehicle->priceHistory()->delete();
        $vehicle->conversions()->delete();
        $vehicle->views()->delete();
        $vehicle->attributeValues()->delete();
        $vehicle->labels()->sync([]);
        $vehicle->equipment()->delete();

        $vehicle->mediaUses()
            ->where('primary', '!=', 1)
            ->delete();

        $vehicle->purged_at = now();
        $vehicle->save();
    }

    private function fullPurge(Vehicle $vehicle): void
    {
        $vehicle->mediaUses()->delete();
        $vehicle->forceDelete();
    }
}
