<?php

namespace App\Listeners;

use Mtc\MercuryDataModels\VehicleCheckFailure;
use Mtc\VehicleValuation\Events\ValuationFailed;

class LogValuationFailure
{
    public function handle(ValuationFailed $event): void
    {
        $failure = VehicleCheckFailure::firstOrCreate(
            [
                'type' => 'valuation',
                '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');
        }
    }
}
