<?php

namespace Tests\Tenant;

use App\Listeners\LogLookupFailure;
use Mtc\MercuryDataModels\VehicleCheckFailure;
use Mtc\VehicleLookup\Events\LookupFailed;
use Tests\TenantTestCase;

class LogLookupFailureTest extends TenantTestCase
{
    public function testItLogsALookupFailure()
    {
        $listener = new LogLookupFailure();
        $listener->handle(new LookupFailed(
            registration: 'AB12CDE',
            mileage: 50000,
            driver: 'AutoTrader',
            exception: new \Exception('Service unavailable'),
        ));

        $this->assertDatabaseHas('vehicle_check_failures', [
            'type' => 'lookup',
            'registration' => 'AB12CDE',
            'mileage' => 50000,
            'driver' => 'AutoTrader',
            'error' => 'Service unavailable',
            'hits' => 1,
        ]);
    }

    public function testUpdates()
    {
        $listener = new LogLookupFailure();

        $listener->handle(new LookupFailed(
            registration: 'AB12CDE',
            mileage: 50000,
            driver: 'AutoTrader',
            exception: new \Exception('Service unavailable'),
        ));

        $listener->handle(new LookupFailed(
            registration: 'AB12CDE',
            mileage: 50000,
            driver: 'AutoTrader',
            exception: new \Exception('Timeout error'),
        ));

        $failure = VehicleCheckFailure::where('registration', 'AB12CDE')
            ->where('type', 'lookup')
            ->first();
        $this->assertEquals('Timeout error', $failure->error);
        $this->assertEquals(2, $failure->hits);
    }

    public function testDifferentMileageCreatesNewFailureRecord()
    {
        $listener = new LogLookupFailure();

        $listener->handle(new LookupFailed(
            registration: 'AB12CDE',
            mileage: 50000,
            driver: 'AutoTrader',
            exception: new \Exception('Service unavailable'),
        ));

        $listener->handle(new LookupFailed(
            registration: 'AB12CDE',
            mileage: 60000,
            driver: 'AutoTrader',
            exception: new \Exception('Service unavailable'),
        ));

        $this->assertCount(2, VehicleCheckFailure::where('registration', 'AB12CDE')
            ->where('type', 'lookup')
            ->get());
    }
}
