<?php

namespace Tests\Tenant;

use App\Listeners\LogValuationFailure;
use Mtc\MercuryDataModels\VehicleCheckFailure;
use Mtc\VehicleValuation\Events\ValuationFailed;
use Tests\TenantTestCase;
use Tests\UserForTenant;

class LogValuationFailureTest extends TenantTestCase
{
    use UserForTenant;

    public function testItLogsAValuationFailure()
    {
        $listener = new LogValuationFailure();
        $listener->handle(new ValuationFailed(
            registration: 'AB12CDE',
            mileage: 50000,
            driver: 'AutoTrader',
            exception: new \Exception('Service unavailable'),
        ));

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

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

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

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

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

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

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

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

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