<?php

use App\Jobs\BulkPolicyDeleteJob;
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 delete sync execution updates policies immediately', function () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create();
    $policies = Policy::factory()->count(10)->create(['tenant_id' => $tenant->id]);
    $policyIds = $policies->pluck('id')->toArray();

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

    // Simulate Sync execution
    BulkPolicyDeleteJob::dispatchSync($run->id);

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

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

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