<?php

namespace App\Listeners;

use Mtc\MercuryDataModels\VehicleCheckFailure;
use Mtc\VehicleLookup\Events\LookupFailed;

class LogLookupFailure
{
    public function handle(LookupFailed $event): void
    {
        $failure = VehicleCheckFailure::firstOrCreate(
            [
                'type' => 'lookup',
                'registration' => $event->registration,
                'mileage' => $event->mileage,
            ],
            [
                'driver' => $event->driver,
                'error' => $event->exception->getMessage(),
            ]
        );

        if (!$failure->wasRecentlyCreated) {
            $failure->update([
                'error' => $event->exception->getMessage(),
            ]);
            $failure->increment('hits');
        }
    }
}
