<?php

use App\Filament\Resources\InventoryItemResource\Pages\ListInventoryItems;
use App\Models\InventorySyncRun;
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Services\Inventory\InventorySyncService;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;

uses(\Illuminate\Foundation\Testing\RefreshDatabase::class);

it('rejects cross-tenant run starts (403) with no run records created', function () {
    Queue::fake();

    [$user, $tenantA] = createUserWithTenant(role: 'owner');
    $tenantB = Tenant::factory()->create();

    $this->actingAs($user);
    Filament::setTenant($tenantA, true);

    $sync = app(InventorySyncService::class);
    $allTypes = $sync->defaultSelectionPayload()['policy_types'];

    Livewire::test(ListInventoryItems::class)
        ->callAction('run_inventory_sync', data: ['tenant_id' => $tenantB->getKey(), 'policy_types' => $allTypes])
        ->assertStatus(403);

    Queue::assertNothingPushed();

    expect(InventorySyncRun::query()->where('tenant_id', $tenantB->id)->exists())->toBeFalse();
    expect(OperationRun::query()->where('tenant_id', $tenantB->id)->exists())->toBeFalse();
});
