<?php

namespace App\Console\Commands;

use App\MediaRepository;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Mtc\MercuryDataModels\Media;

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

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

    /**
     * Execute the console command.
     */
    public function handle()
    {
        Media::query()
            ->whereNotNull('source_filename')
            ->whereHas('uses', fn($query) => $query->where('owner_type', 'vehicle'))
            ->get()
            ->each(fn(Media $media) => $this->clean($media));

        return self::SUCCESS;
    }

    public function clean(Media $media): void
    {
        try {
            $media->refresh();
        } catch (ModelNotFoundException $exception) {
            // already removed this media entry
            return;
        }
        $other_versions = Media::query()
            ->where('source_filename', $media->source_filename)
            ->where('image_provider', $media->image_provider)
            ->where('id', '!=', $media->id)
            ->get()
            ->each(function ($duplicate) {
                $duplicate->uses()->delete();
                $duplicate->delete();
            });
    }
}
