<?php

namespace App\Jobs;

use App\Events\VehicleUpdated;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Mtc\ContentManager\Facades\Media;
use Mtc\MercuryDataModels\Vehicle;

class ImportImageListNotificationJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public $timeout = 0;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(
        private ?Vehicle $vehicle = null,
        private array $imageList = [],
        private $notification = null,
        private readonly string $provider = '',
    ) {
        $this->onQueue('bulk-media');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        collect($this->imageList)
            ->map(function ($image) {
                try {
                    $media = Media::importImageFromUrl($image);
                    $media->tags()->create(['tag' => 'vehicle']);
                    return $media;
                } catch (\Exception $exception) {
                    if ($exception->getMessage() !== 'Unable to load file') {
                        Log::warning('Failed to import image', [
                            'provider' => $this->provider,
                            'vehicle_id' => $this->vehicle?->id,
                            'image_data' => $image,
                            'error' => $exception->getMessage(),
                        ]);
                    }
                    return null;
                }
            })
            ->filter()
            ->tap(function (Collection $media) {
                $mediaIds = $media->pluck('id')->toArray();
                if (!empty($this->vehicle)) {
                    Media::setUsesForModel($mediaIds, $this->vehicle, ['primary' => true]);
                } elseif (!empty($this->notification)) {
                    $notificationData = $this->notification->data;
                    $notificationData['media'] = $mediaIds;
                    $this->notification->data = $notificationData;
                    $this->notification->save();
                }
            });
        if ($this->vehicle) {
            VehicleUpdated::dispatch($this->vehicle);
        }
    }
}
