<?php

use App\Jobs\BulkPolicyUnignoreJob;
use App\Models\OperationRun;
use App\Models\Policy;
use App\Models\ManagedEnvironment;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

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

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

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

    $opRun = OperationRun::create([
        'managed_environment_id' => $tenant->id,
        'user_id' => $user->id,
        'initiator_name' => $user->name,
        'type' => 'policy.unignore',
        'status' => 'queued',
        'outcome' => 'pending',
        'run_identity_hash' => 'policy-unignore-test',
        'context' => [
            'policy_ids' => $policyIds,
        ],
    ]);

    BulkPolicyUnignoreJob::dispatchSync(
        tenantId: (int) $tenant->getKey(),
        userId: (int) $user->getKey(),
        policyIds: $policyIds,
        operationRun: $opRun,
    );

    $opRun->refresh();

    expect($opRun->status)->toBe('completed');

    $counts = is_array($opRun->summary_counts) ? $opRun->summary_counts : [];
    expect((int) ($counts['processed'] ?? 0))->toBe(5);
    expect((int) ($counts['succeeded'] ?? 0))->toBe(5);
    expect((int) ($counts['failed'] ?? 0))->toBe(0);

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