<?php

namespace Tests\Tenant;

use App\Facades\Settings;
use App\Services\VehicleBulkUpdateService;
use Database\Seeders\Tenant\FinanceProductRestrictionSetting;
use Database\Seeders\Tenant\FinanceSettingSeeder;
use Illuminate\Support\Facades\Bus;
use Mtc\MercuryDataModels\Finance\Jobs\FetchVehicleFinanceData;
use Mtc\MercuryDataModels\Vehicle;
use Tests\TenantTestCase;

class VehicleBulkUpdateServiceTest extends TenantTestCase
{
    public function testRequestFinanceQuotesSkipsVehiclesWithStopFinanceSync(): 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');

        $optedIn = Vehicle::factory()->create([
            'price' => 10000,
            'cap_id' => '11111',
            'data' => [],
        ]);

        $optedOut = Vehicle::factory()->create([
            'price' => 10000,
            'cap_id' => '22222',
            'data' => ['stop_finance_sync' => true],
        ]);

        $result = new VehicleBulkUpdateService()
            ->requestFinanceQuotes([$optedIn->id, $optedOut->id]);

        $this->assertEquals(1, $result['requested']);
        $this->assertEquals(1, $result['failed']);

        Bus::assertDispatchedTimes(FetchVehicleFinanceData::class, 1);
    }

    public function testArchiveSoftDeletesSelectedVehiclesAndSkipsTrashed(): void
    {
        $active = Vehicle::factory(2)->create();
        $alreadyArchived = Vehicle::factory()->create();
        $alreadyArchived->delete();

        $ids = $active->pluck('id')->push($alreadyArchived->id)->all();
        $archived = new VehicleBulkUpdateService()->archive($ids);

        $this->assertSame(2, $archived, 'Already-archived vehicles must not be re-counted.');
        foreach ($active as $vehicle) {
            $this->assertTrue($vehicle->fresh()->trashed());
        }
        $this->assertSame(0, Vehicle::query()->whereIn('id', $ids)->count());
        $this->assertSame(3, Vehicle::withTrashed()->whereIn('id', $ids)->count());
    }
}
