<?php

namespace Tests\Unit;

use App\Events\VehiclePriceChangedDuringStockSync;
use App\Facades\Settings;
use App\Listeners\RefreshFinanceOnVehiclePriceChange;
use Database\Seeders\Tenant\FinanceProductRestrictionSetting;
use Database\Seeders\Tenant\FinanceSettingSeeder;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\Bus;
use Mtc\MercuryDataModels\Finance\Jobs\FetchVehicleFinanceData;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleFinance;
use Tests\TenantTestCase;
use Tests\TestCase;

class RefreshFinanceOnVehiclePriceChangeTest extends TenantTestCase
{
    public function testDeletesCachedFinanceQuotesOnPriceChange(): void
    {
        $vehicle = Vehicle::factory()->create([
            'price' => 10000,
            'monthly_price' => 199,
            'monthly_cost_type' => 'pcp',
        ]);

        // Create cached finance quotes from provider
        VehicleFinance::factory()->create([
            'vehicle_id' => $vehicle->id,
            'provider' => 'codeweavers',
            'monthly_price' => 199,
        ]);
        VehicleFinance::factory()->create([
            'vehicle_id' => $vehicle->id,
            'provider' => 'codeweavers',
            'monthly_price' => 250,
        ]);

        $this->assertCount(2, $vehicle->financeExamples);

        $event = new VehiclePriceChangedDuringStockSync($vehicle, 'test-provider');
        $listener = new RefreshFinanceOnVehiclePriceChange();
        $listener->handle($event);

        $vehicle->refresh();

        // Assert cached quotes are deleted
        $this->assertCount(0, $vehicle->financeExamples);

        // Assert vehicle finance fields are cleared
        $this->assertNull($vehicle->monthly_price);
        $this->assertNull($vehicle->monthly_cost_type);
    }

    public function testPreservesManualFinanceEntriesOnPriceChange(): void
    {
        $vehicle = Vehicle::factory()->create([
            'price' => 10000,
            'monthly_price' => 199,
            'monthly_cost_type' => 'pcp',
        ]);

        // Create a manual finance entry
        VehicleFinance::factory()->create([
            'vehicle_id' => $vehicle->id,
            'provider' => 'manual',
            'monthly_price' => 180,
        ]);

        // Create cached finance quotes from provider
        VehicleFinance::factory()->create([
            'vehicle_id' => $vehicle->id,
            'provider' => 'codeweavers',
            'monthly_price' => 199,
        ]);

        $this->assertCount(2, $vehicle->financeExamples);

        $event = new VehiclePriceChangedDuringStockSync($vehicle, 'test-provider');
        $listener = new RefreshFinanceOnVehiclePriceChange();
        $listener->handle($event);

        $vehicle->refresh();

        // Assert only manual entry is preserved
        $this->assertCount(1, $vehicle->financeExamples);
        $this->assertEquals('manual', $vehicle->financeExamples->first()->provider);
    }

    public function testRequestsNewQuotesWhenProviderEnabled(): void
    {
        Bus::fake();

        $this->seed(FinanceSettingSeeder::class);
        $this->seed(FinanceProductRestrictionSetting::class);
        Settings::update('finance-codeweavers-enabled', true);
        Settings::update('finance-codeweavers-api_key', 'test-key');
        Settings::update('finance-codeweavers-username', 'test-user');
        Settings::update('finance-codeweavers-password', 'test-pass');
        Settings::update('finance-batch-update', false);

        $vehicle = Vehicle::factory()->create([
            'price' => 10000,
            'registration_number' => 'AB12CDE',
            'cap_id' => '12345',
        ]);

        $event = new VehiclePriceChangedDuringStockSync($vehicle, 'test-provider');
        $listener = new RefreshFinanceOnVehiclePriceChange();
        $listener->handle($event);

        Bus::assertDispatched(FetchVehicleFinanceData::class);
    }

    public function testDoesNotRequestNewQuotesWhenBatchUpdateEnabled(): void
    {
        Bus::fake();

        $this->seed(FinanceSettingSeeder::class);
        $this->seed(FinanceProductRestrictionSetting::class);
        Settings::update('finance-codeweavers-enabled', true);
        Settings::update('finance-codeweavers-api_key', 'test-key');
        Settings::update('finance-codeweavers-username', 'test-user');
        Settings::update('finance-codeweavers-password', 'test-pass');
        Settings::update('finance-batch-update', true);

        $vehicle = Vehicle::factory()->create([
            'price' => 10000,
            'registration_number' => 'AB12CDE',
            'cap_id' => '12345',
        ]);

        $event = new VehiclePriceChangedDuringStockSync($vehicle, 'test-provider');
        $listener = new RefreshFinanceOnVehiclePriceChange();
        $listener->handle($event);

        Bus::assertNotDispatched(FetchVehicleFinanceData::class);
    }
}
