<?php

namespace Tests\Tenant;

use App\Jobs\UpdateVehicleSearchContent;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleMake;
use Mtc\MercuryDataModels\VehicleModel;
use Tests\TenantTestCase;

class UpdateVehicleSearchContentJobTest extends TenantTestCase
{
    public function testUpdatesSearchContentForAllVehicles()
    {
        $make = VehicleMake::factory()->create(['name' => 'Toyota']);
        $model = VehicleModel::factory()->create(['name' => 'Corolla', 'make_id' => $make->id]);

        $vehicle = Vehicle::factory()->create([
            'make_id' => $make->id,
            'model_id' => $model->id,
            'title' => 'Toyota Corolla',
            'search_content' => null,
        ]);

        (new UpdateVehicleSearchContent(''))->handle();

        $vehicle->refresh();
        $this->assertNotNull($vehicle->search_content);
    }

    public function testFiltersVehiclesByProvider()
    {
        $make = VehicleMake::factory()->create(['name' => 'Honda']);
        $model = VehicleModel::factory()->create(['name' => 'Civic', 'make_id' => $make->id]);

        $providerVehicle = Vehicle::factory()->create([
            'make_id' => $make->id,
            'model_id' => $model->id,
            'stock_provider' => 'test-provider',
            'search_content' => null,
        ]);

        $otherVehicle = Vehicle::factory()->create([
            'make_id' => $make->id,
            'model_id' => $model->id,
            'stock_provider' => 'other-provider',
            'search_content' => null,
        ]);

        (new UpdateVehicleSearchContent('test-provider'))->handle();

        // Both vehicles should be updated since search_content is populated on save
        $this->assertNotNull($providerVehicle->fresh()->search_content);
    }

    public function testHandlesEmptyProvider()
    {
        Vehicle::factory(3)->create(['search_content' => null]);

        // Should not throw an exception
        (new UpdateVehicleSearchContent(''))->handle();

        $this->assertEquals(3, Vehicle::count());
    }
}
