<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Collection;
use Mtc\MercuryDataModels\MediaUse;
use Mtc\MercuryDataModels\Vehicle;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove duplicate images for vehicles';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        Vehicle::query()
            ->with('mediaUses.media')
            ->get()
            ->each(fn($vehicle) => $this->checkVehicleForDuplicateImages($vehicle));
    }

    private function checkVehicleForDuplicateImages(Vehicle $vehicle): void
    {
        /** @var Collection $duplicates */
        $duplicates = $vehicle->mediaUses->groupBy(fn(MediaUse $mediaUse) => $mediaUse->media->source_filename)
            ->filter(fn($group, $filename) => !empty($filename) && $group->count() > 1);

        if ($duplicates->isNotEmpty()) {
            $duplicates->each(fn($uses) => $uses
                // Leave 1 image of this duplicate series
                ->skip(1)
                ->each(function (MediaUse $duplicate) {
                    $duplicate->media->delete();
                    $duplicate->delete();
                }));
        }
    }
}
