<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehiclePriceHistory;

class CleanupPriceHistory extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'vehicles:cleanup-price-history '
        . '{--dry-run : Show what would be deleted without actually deleting}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove consecutive duplicate price history entries,'
        . ' keeping the oldest entry for each price change';

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $dryRun = $this->option('dry-run');

        if ($dryRun) {
            $this->info('DRY RUN - No records will be deleted');
        }

        $this->info('Finding duplicate consecutive price history entries...');

        $totalDeleted = 0;
        $vehiclesProcessed = 0;

        Vehicle::query()
            ->withTrashed()
            ->whereHas('priceHistory')
            ->select('id')
            ->chunk(500, function ($vehicles) use ($dryRun, &$totalDeleted, &$vehiclesProcessed) {
                foreach ($vehicles as $vehicle) {
                    $deleted = $this->cleanupVehiclePriceHistory($vehicle->id, $dryRun);
                    $totalDeleted += $deleted;
                    $vehiclesProcessed++;
                }
            });

        $action = $dryRun ? 'would be deleted' : 'deleted';
        $this->info("Processed {$vehiclesProcessed} vehicles");
        $this->info("Total duplicate entries {$action}: {$totalDeleted}");

        return Command::SUCCESS;
    }

    /**
     * Clean up price history for a single vehicle
     */
    private function cleanupVehiclePriceHistory(string $vehicleId, bool $dryRun): int
    {
        $priceHistory = VehiclePriceHistory::query()
            ->where('vehicle_id', $vehicleId)
            ->orderBy('created_at')
            ->orderBy('id')
            ->get();

        if ($priceHistory->count() <= 1) {
            return 0;
        }

        $idsToDelete = [];
        $previousPrice = null;

        foreach ($priceHistory as $entry) {
            $currentPrice = round((float) $entry->price, 2);

            if ($previousPrice !== null && $currentPrice === $previousPrice) {
                // This is a duplicate - mark for deletion
                $idsToDelete[] = $entry->id;
            }

            $previousPrice = $currentPrice;
        }

        if (empty($idsToDelete)) {
            return 0;
        }

        if (!$dryRun) {
            VehiclePriceHistory::query()
                ->whereIn('id', $idsToDelete)
                ->delete();
        }

        return count($idsToDelete);
    }
}
