<?php

namespace App\Modules\ImageSync;

use App\Jobs\ImportImageListNotificationJob;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Mtc\MercuryDataModels\ApiNotification;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\ContentManager\Facades\Media;

class AutoImaging implements ImageSync
{
    use DispatchesJobs;

    public const PROVIDER_NAME = 'auto-imaging';

    public function sync(): void
    {
        $this->retryFromNotifications();
    }

    public static function applyVideoUrls(Vehicle $vehicle, array $data): bool
    {
        $updates = [];

        if (isset($data['Urls'][0])) {
            $updates['interior_video_url'] = $data['Urls'][0];
        }

        if (isset($data['vimeoUrl'])) {
            $updates['main_video_url'] = $data['vimeoUrl'];
        }

        if (isset($data['videoUrl'])) {
            $updates['main_video_url'] = $data['videoUrl'];
        }

        if (empty($updates)) {
            return false;
        }

        $vehicle->update($updates);
        return true;
    }

    private function retryFromNotifications(): void
    {
        ApiNotification::query()
            ->whereNull('processed')
            ->where('provider', self::PROVIDER_NAME)
            ->get()
            ->each(fn (ApiNotification $notification) => $this->handleNotification($notification));
    }

    private function handleNotification(ApiNotification $notification): void
    {
        /** @var Vehicle|null $vehicle */
        $vehicle = Vehicle::query()->where('vrm_condensed', $notification->reference)->latest()->first();
        if (!$vehicle) {
            return;
        }

        self::applyVideoUrls($vehicle, $notification->data ?? []);

        $images = $notification->data['images'] ?? [];
        if ($this->hasCorrectVehicleImageCount($vehicle, $images)) {
            $notification->update(['processed' => 1]);
            return;
        }

        if (!empty($notification['data']['media'])) {
            Media::setUsesForModel(
                $notification['data']['media'],
                $vehicle,
                ['primary' => true]
            );

            $notification->update([
                'processed' => true
            ]);
        } else {
            $this->attemptRetry($vehicle, $images);
        }
    }

    private function hasCorrectVehicleImageCount(Vehicle $vehicle, array $images): bool
    {
        return $vehicle->mediaUses()->count() >= count($images);
    }

    private function attemptRetry(Vehicle $vehicle, array $images): void
    {
        $this->dispatch(new ImportImageListNotificationJob($vehicle, $images, null, 'auto-imaging'));
    }
}
