<?php

use App\Jobs\BulkPolicyUnignoreJob;
use App\Models\Policy;
use App\Models\Tenant;
use App\Models\User;
use App\Services\BulkOperationService;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('bulk restore (unignore) clears ignored_at for selected policies', function () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create();

    $policies = Policy::factory()
        ->count(5)
        ->create([
            'tenant_id' => $tenant->id,
            'ignored_at' => now(),
        ]);

    $policyIds = $policies->pluck('id')->toArray();

    $service = app(BulkOperationService::class);
    $run = $service->createRun($tenant, $user, 'policy', 'unignore', $policyIds, count($policyIds));

    BulkPolicyUnignoreJob::dispatchSync($run->id);

    $run->refresh();

    expect($run->status)->toBe('completed')
        ->and($run->processed_items)->toBe(5)
        ->and($run->audit_log_id)->not->toBeNull();

    expect(\App\Models\AuditLog::where('action', 'bulk.policy.unignore.completed')->exists())->toBeTrue();

    $policies->each(function (Policy $policy): void {
        expect($policy->refresh()->ignored_at)->toBeNull();
    });
});
