<?php

namespace App\Jobs;

use App\Facades\Settings;
use App\Modules\ImageSync\AutosOnShow as AutosOnShowSync;
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\Collection;
use Illuminate\Support\Facades\Log;
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, private $notification = null)
    {
        $this->onQueue('media');
    }

    /**
     * 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'],
                        '',
                        AutosOnShowSync::PROVIDER_NAME
                    );
                    $media->tags()->create(['tag' => 'vehicle']);
                    return $media;
                } catch (\Exception $exception) {
                    Log::warning('Failed to import image', [
                        'provider' => AutosOnShowSync::PROVIDER_NAME,
                        'vehicle_id' => $this->vehicle->id,
                        'image_data' => $image,
                        'error' => $exception,
                    ]);
                    return null;
                }
            })
            ->filter()
            ->tap(function (Collection $media) {
                $mediaIds = $media->pluck('id')->toArray();

                if (!empty($this->vehicle)) {
                    $removeOthers = Settings::get('image-sync-autos-on-show-remove-other-images') ?? false;
                    Media::setUsesForModel($mediaIds, $this->vehicle, ['primary' => true], $removeOthers);
                }

                if (!empty($this->notification)) {
                    $notificationData = $this->notification->data;
                    $notificationData['media'] = $mediaIds;
                    $this->notification->data = $notificationData;
                    $this->notification->save();
                }
            });
    }
}
