<?php

namespace App\Modules\ImageSync;

use App\Enums\AutosOnShowNotificationType;
use App\Jobs\ImportAutosOnShowFilesJob;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Mtc\MercuryDataModels\ApiNotification;
use Mtc\MercuryDataModels\Vehicle;

class AutosOnShow implements ImageSync
{
    use DispatchesJobs;

    public const PROVIDER_NAME = 'autos-on-show';

    protected const ACTIONABLE_NOTIFICATION_TYPES = [
        AutosOnShowNotificationType::VEHICLE_UPLOADED->value,
        AutosOnShowNotificationType::MEDIA_BACKGROUND_REPLACED->value,
        AutosOnShowNotificationType::VEHICLE_REIMAGED->value,
        AutosOnShowNotificationType::ADDITIONAL->value,
        AutosOnShowNotificationType::VEHICLE_POST_BACKGROUND_QC_COMPLETE->value,
        AutosOnShowNotificationType::VEHICLE_IMAGE_SEQUENCE_CHANGED->value,
        AutosOnShowNotificationType::VEHICLE_IDENTIFIER_CHANGED->value,
    ];

    public function sync(): void
    {
        // TODO: check if we need to initialise tenancy here
        // e.g. if this is called from API

        $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
    {
        $vehicle = Vehicle::query()
            ->where('vrm_condensed', $notification->reference)
            ->orWhere('vin', $notification->reference)
            ->latest()
            ->first();

        if (!$vehicle) {
            return;
        }

        if (in_array($notification->data['notificationTypeId'] ?? null, self::ACTIONABLE_NOTIFICATION_TYPES)) {
            $this->attemptRetry($vehicle);
        }

        $notification->update([
            'processed' => true,
        ]);
    }

    private function attemptRetry(Vehicle $vehicle): void
    {
        $this->dispatch(new ImportAutosOnShowFilesJob($vehicle, app(\App\Services\AutosOnShow::class)));
    }
}
