<?php

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

uses(RefreshDatabase::class);

test('bulk delete requires confirmation string for large batches', function () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create();
    $user->tenants()->syncWithoutDetaching([
        $tenant->getKey() => ['role' => 'owner'],
    ]);

    Filament::setTenant($tenant, true);
    $policies = Policy::factory()->count(20)->create(['tenant_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 () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create();
    $user->tenants()->syncWithoutDetaching([
        $tenant->getKey() => ['role' => 'owner'],
    ]);

    Filament::setTenant($tenant, true);
    $policies = Policy::factory()->count(20)->create(['tenant_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 () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create();
    $user->tenants()->syncWithoutDetaching([
        $tenant->getKey() => ['role' => 'owner'],
    ]);

    Filament::setTenant($tenant, true);
    $policies = Policy::factory()->count(10)->create(['tenant_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());
});
