<?php

namespace App\Modules\ImageSync;

use App\Jobs\ImportAutoImagingFilesJob;
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();
    }

    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;
        }

        $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 ImportAutoImagingFilesJob($vehicle, $images));
    }
}
