<?php

use App\Filament\Pages\DriftLanding;
use App\Jobs\GenerateDriftFindingsJob;
use App\Models\BulkOperationRun;
use App\Models\InventorySyncRun;
use App\Support\RunIdempotency;
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(),
    ]);

    $idempotencyKey = RunIdempotency::buildKey(
        tenantId: (int) $tenant->getKey(),
        operationType: 'drift.generate',
        targetId: $scopeKey,
        context: [
            'scope_key' => $scopeKey,
            'baseline_run_id' => (int) $baseline->getKey(),
            'current_run_id' => (int) $current->getKey(),
        ],
    );

    BulkOperationRun::factory()->for($tenant)->for($user)->create([
        'resource' => 'drift',
        'action' => 'generate',
        'status' => 'completed',
        'idempotency_key' => $idempotencyKey,
        'item_ids' => [$scopeKey],
        'total_items' => 1,
        'processed_items' => 1,
        'succeeded' => 1,
        'failed' => 0,
        'skipped' => 0,
    ]);

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

    Queue::assertNothingPushed();

    expect(BulkOperationRun::query()
        ->where('tenant_id', $tenant->getKey())
        ->where('idempotency_key', $idempotencyKey)
        ->count())->toBe(1);

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