<?php

use App\Filament\Resources\PolicyResource;
use App\Models\Policy;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

test('bulk delete requires confirmation string for large batches', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    setAdminPanelContext($tenant);
    $policies = Policy::factory()->count(20)->create(['managed_environment_id' => $tenant->id]);

    Livewire::actingAs($user)
        ->test(PolicyResource\Pages\ListPolicies::class)
        ->callTableBulkAction('bulk_delete', $policies, data: [
            'confirmation' => 'DELETE',
        ])
        ->assertHasNoTableBulkActionErrors();

    $policies->each(fn ($p) => expect($p->refresh()->ignored_at)->not->toBeNull());
});

test('bulk delete fails with incorrect confirmation string', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    setAdminPanelContext($tenant);
    $policies = Policy::factory()->count(20)->create(['managed_environment_id' => $tenant->id]);

    Livewire::actingAs($user)
        ->test(PolicyResource\Pages\ListPolicies::class)
        ->callTableBulkAction('bulk_delete', $policies, data: [
            'confirmation' => 'delete', // lowercase, should fail
        ])
        ->assertHasTableBulkActionErrors(['confirmation']);

    $policies->each(fn ($p) => expect($p->refresh()->ignored_at)->toBeNull());
});

test('bulk delete does not require confirmation string for small batches', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    setAdminPanelContext($tenant);
    $policies = Policy::factory()->count(10)->create(['managed_environment_id' => $tenant->id]);

    Livewire::actingAs($user)
        ->test(PolicyResource\Pages\ListPolicies::class)
        ->callTableBulkAction('bulk_delete', $policies, data: [])
        ->assertHasNoTableBulkActionErrors();

    $policies->each(fn ($p) => expect($p->refresh()->ignored_at)->not->toBeNull());
});
