<?php

use App\Filament\Pages\DriftLanding;
use App\Jobs\GenerateDriftFindingsJob;
use App\Models\InventorySyncRun;
use App\Models\OperationRun;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;

test('opening Drift does not re-dispatch when the last run completed with zero findings', function () {
    Queue::fake();

    [$user, $tenant] = createUserWithTenant(role: 'manager');
    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    $scopeKey = hash('sha256', 'scope-zero-findings');

    $baseline = InventorySyncRun::factory()->for($tenant)->create([
        'selection_hash' => $scopeKey,
        'selection_payload' => ['policy_types' => ['settingsCatalogPolicy']],
        'status' => InventorySyncRun::STATUS_SUCCESS,
        'finished_at' => now()->subDays(2),
    ]);

    $current = InventorySyncRun::factory()->for($tenant)->create([
        'selection_hash' => $scopeKey,
        'selection_payload' => ['policy_types' => ['settingsCatalogPolicy']],
        'status' => InventorySyncRun::STATUS_SUCCESS,
        'finished_at' => now()->subDay(),
    ]);

    OperationRun::create([
        'tenant_id' => $tenant->getKey(),
        'user_id' => $user->getKey(),
        'initiator_name' => $user->name,
        'type' => 'drift.generate',
        'status' => 'completed',
        'outcome' => 'succeeded',
        'run_identity_hash' => 'drift-zero-findings',
        'summary_counts' => [
            'total' => 1,
            'processed' => 1,
            'succeeded' => 1,
            'failed' => 0,
            'created' => 0,
        ],
        'context' => [
            'scope_key' => $scopeKey,
            'baseline_run_id' => (int) $baseline->getKey(),
            'current_run_id' => (int) $current->getKey(),
        ],
    ]);

    Livewire::test(DriftLanding::class)
        ->assertSet('state', 'ready')
        ->assertSet('scopeKey', $scopeKey);

    Queue::assertNothingPushed();

    Queue::assertNotPushed(GenerateDriftFindingsJob::class);
});
