<?php

namespace Tests\Tenant;

use App\Facades\Feature;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Queue;
use Mtc\MercuryDataModels\Setting;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleMake;
use Mtc\MercuryDataModels\VehicleModel;
use Tests\TenantTestCase;

class MakePlaceholderImageCacheTest extends TenantTestCase
{
    protected function setUp(): void
    {
        parent::setUp();
        Queue::fake();
    }

    public function testMakePlaceholderQueryIsCachedPerMake()
    {
        Feature::setEnabled(tenant(), ['makes-placeholders']);

        $make = VehicleMake::factory()->create();
        $model = VehicleModel::factory()->create(['make_id' => $make->id]);

        Setting::query()->create([
            'tab' => 'test',
            'section' => 'test',
            'group' => 'test',
            'name' => 'test',
            'config_key' => 'placeholder-image-vehicle-make-' . $make->id,
            'type' => 'media',
            'value' => null,
        ]);

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

        DB::enableQueryLog();

        $response = $this->postJson(route('vehicles.index'));

        $response->assertStatus(200);

        $queries = collect(DB::getQueryLog());
        $placeholderQueries = $queries->filter(
            fn($q) => str_contains($q['query'], 'placeholder-image-vehicle-make-')
        );

        $this->assertLessThanOrEqual(1, $placeholderQueries->count(),
            "Expected at most 1 placeholder-image-vehicle-make query, got {$placeholderQueries->count()}"
        );
    }
}
