<?php

namespace App\Jobs;

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\Contracts\Media as MediaModel;
use Mtc\ContentManager\Facades\Media;
use Mtc\MercuryDataModels\ApiNotification;
use Mtc\MercuryDataModels\MediaUse;
use Mtc\MercuryDataModels\Vehicle;

class ImportAutoImagingFilesJob 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
    ) {
        $this->onQueue('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' => 'auto-imaging',
                            '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();
                }
            });
    }
}
