<?php

namespace App\Jobs;

use App\Services\AutosOnShow;
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\Facades\Log;
use Mtc\ContentManager\Contracts\Media as MediaModel;
use Mtc\ContentManager\Facades\Media;
use Mtc\MercuryDataModels\Vehicle;

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

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(private Vehicle $vehicle, private AutosOnShow $service)
    {
        $this->onQueue('export');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $resultData = $this->service->getVehicleMedia($this->vehicle->registration_number);

        if (!empty($resultData['images'])) {
            $this->saveImages($resultData['images']);
        }

        if (!empty($resultData['videourl'])) {
            $this->vehicle->update([
                'main_video_url' => $resultData['videourl']
            ]);
        }
    }

    /**
     * Import and persist images against vehicle
     *
     * @param array $images
     * @return void
     */
    private function saveImages(array $images)
    {
        $this->vehicle->mediaUses()->delete();
        collect($images)
            ->filter()
            ->map(function ($image) {
                try {
                    $media =  Media::importImageFromUrl($image['large']);
                    $media->tags()->create(['tag' => 'vehicle']);
                    return $media;
                } catch (\Exception $exception) {
                    Log::warning('Failed to import image', [
                        'provider' => 'autos-on-show',
                        'vehicle_id' => $this->vehicle->id,
                        'image_data' => $image,
                        'error' => $exception,
                    ]);
                    return null;
                }
            })
            ->filter()
            ->each(fn (MediaModel $media, $index) => $this->vehicle->mediaUses()->create([
                'media_id' => $media->id,
                'order' => $index
            ]));
    }
}
