<?php

namespace Tests\Tenant;

use App\Filter\FilterIndex;
use App\Jobs\RefreshFilterIndexJob;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleMake;
use Mtc\MercuryDataModels\VehicleModel;
use Tests\TenantTestCase;

class RefreshFilterIndexJobTest extends TenantTestCase
{
    public function testJobRunsWithoutException()
    {
        // Create some test data
        $make = VehicleMake::factory()->create(['name' => 'Toyota']);
        $model = VehicleModel::factory()->create(['name' => 'Camry', 'make_id' => $make->id]);
        Vehicle::factory(3)->create([
            'make_id' => $make->id,
            'model_id' => $model->id,
        ]);

        // Job should complete without exception
        (new RefreshFilterIndexJob())->handle();

        $this->assertTrue(true);
    }

    public function testJobIndexesFilters()
    {
        $make = VehicleMake::factory()->create(['name' => 'Honda']);
        $model = VehicleModel::factory()->create(['name' => 'Accord', 'make_id' => $make->id]);
        Vehicle::factory(5)->create([
            'make_id' => $make->id,
            'model_id' => $model->id,
        ]);

        $initialCount = FilterIndex::query()->count();

        (new RefreshFilterIndexJob())->handle();

        // Filter index should have entries after job runs
        // The exact count depends on configured filters
        $this->assertGreaterThanOrEqual($initialCount, FilterIndex::query()->count());
    }

    public function testJobHandlesEmptyDatabase()
    {
        // Ensure no vehicles exist
        Vehicle::query()->forceDelete();

        // Job should handle empty database gracefully
        (new RefreshFilterIndexJob())->handle();

        $this->assertTrue(true);
    }

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

        Vehicle::factory()->create([
            'make_id' => $make->id,
            'model_id' => $model->id,
            'is_published' => true,
        ]);

        (new RefreshFilterIndexJob())->handle();

        // Verify job completed - specific filter index behavior depends on configuration
        $this->assertTrue(true);
    }
}
