<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Mtc\ContentManager\Facades\Media;
use Mtc\MercuryDataModels\MediaUse;
use Mtc\MercuryDataModels\Vehicle;

class PurgeOrphanedProviderImages extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'media:purge-orphaned-provider-images';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove media files that are from providers and are not attached to anything';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        MediaUse::query()
            ->with('media')
            ->whereHas('media', fn($query) => $query->whereNull('external')->whereNotNull('image_provider'))
            ->where('primary', 0)
            ->where('owner_type', 'vehicle')
            ->chunk(100, fn ($chunk) => $this->checkMediaUses($chunk));

        return self::SUCCESS;
    }

    private function checkMediaUses(Collection $chunk): void
    {
        $not_purged = Vehicle::withTrashed()
            ->whereIn('id', $chunk->pluck('owner_id'))
            ->whereNull('purged_at')
            ->pluck('id');
        $chunk->each(function (MediaUse $use) use ($not_purged) {
            // Vehicle not purged, not ready to be removed
            if ($not_purged->contains($use->owner_id)) {
                return;
            }

            // Has other uses, can only remove the use, not file itself
            if ($use->media->uses()->count() > 1) {
                $use->delete();
                return;
            }

            $this->output->text("Purging $use->media_id - {$use->media->src}");
            Media::destroyMedia($use->media_id);
        });
    }
}
