<?php

use App\Filament\Resources\BulkOperationRunResource;
use App\Models\BulkOperationRun;
use App\Models\Tenant;
use App\Models\User;

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

test('bulk operation runs are listed for the active tenant', function () {
    $tenantA = Tenant::factory()->create();
    $tenantB = Tenant::factory()->create();

    BulkOperationRun::factory()->create([
        'tenant_id' => $tenantA->getKey(),
        'resource' => 'tenant_a',
        'action' => 'alpha',
    ]);

    BulkOperationRun::factory()->create([
        'tenant_id' => $tenantB->getKey(),
        'resource' => 'tenant_b',
        'action' => 'beta',
    ]);

    $user = User::factory()->create();
    $user->tenants()->syncWithoutDetaching([
        $tenantA->getKey() => ['role' => 'owner'],
        $tenantB->getKey() => ['role' => 'owner'],
    ]);

    $this->actingAs($user)
        ->get(BulkOperationRunResource::getUrl('index', tenant: $tenantA))
        ->assertOk()
        ->assertSee('tenant_a')
        ->assertDontSee('tenant_b');
});

test('bulk operation run view is forbidden cross-tenant (403)', function () {
    $tenantA = Tenant::factory()->create();
    $tenantB = Tenant::factory()->create();

    $runB = BulkOperationRun::factory()->create([
        'tenant_id' => $tenantB->getKey(),
        'resource' => 'tenant_b',
        'action' => 'beta',
    ]);

    $user = User::factory()->create();
    $user->tenants()->syncWithoutDetaching([
        $tenantA->getKey() => ['role' => 'owner'],
        $tenantB->getKey() => ['role' => 'owner'],
    ]);

    $this->actingAs($user)
        ->get(BulkOperationRunResource::getUrl('view', ['record' => $runB], tenant: $tenantA))
        ->assertForbidden();
});

test('readonly users can view bulk operation runs for their tenant', function () {
    $tenant = Tenant::factory()->create();

    $run = BulkOperationRun::factory()->create([
        'tenant_id' => $tenant->getKey(),
        'resource' => 'drift',
        'action' => 'generate',
    ]);

    $user = User::factory()->create();
    $user->tenants()->syncWithoutDetaching([
        $tenant->getKey() => ['role' => 'readonly'],
    ]);

    $this->actingAs($user)
        ->get(BulkOperationRunResource::getUrl('index', tenant: $tenant))
        ->assertOk()
        ->assertSee('drift')
        ->assertSee('generate');

    $this->actingAs($user)
        ->get(BulkOperationRunResource::getUrl('view', ['record' => $run], tenant: $tenant))
        ->assertOk()
        ->assertSee('drift')
        ->assertSee('generate')
        ->assertSee('Drift findings');
});
