<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Mtc\ContentManager\Facades\Media as MediaFacade;
use Mtc\MercuryDataModels\ApiNotification;
use Mtc\MercuryDataModels\Media;

class RemovePreviousAutoloadItFileVersions implements ShouldQueue, ShouldBeUnique
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(private readonly ApiNotification $notification)
    {
        $this->onQueue('bulk-media');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(): void
    {
        $images = explode(',', $this->notification->data['picturerefs'] ?? '');
        $old_file_names = $this->getImagesFromPreviousNotifications()
            ->reject(fn ($image) => in_array($image, $images));
        $this->removeIfNotUsed($old_file_names);
    }

    private function removeIfNotUsed($old_file_names): void
    {
        $media_ids = Media::query()
            ->whereIn('source_filename', $old_file_names)
            ->where('image_provider', $this->notification->provider)
            ->whereDoesntHave('uses')
            ->pluck('id')
            ->toArray();

        MediaFacade::destroyMedia($media_ids);
    }

    private function getImagesFromPreviousNotifications(): Collection
    {
        return ApiNotification::query()
            ->where('provider', $this->notification->provider)
            ->where('reference', $this->notification->reference)
            ->where('created_at', '<', $this->notification->created_at)
            ->get()
            ->map(fn (ApiNotification $notification) => explode(',', $notification->data['picturerefs'] ?? ''))
            ->flatten(1)
            ->filter();
    }
}
