<?php

use App\Jobs\BulkPolicyDeleteJob;
use App\Jobs\BulkPolicyExportJob;
use App\Models\Tenant;
use App\Models\User;
use App\Services\BulkOperationService;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);
test('bulk delete aborts when more than half of items fail', function () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create();

    $service = app(BulkOperationService::class);
    $run = $service->createRun($tenant, $user, 'policy', 'delete', [100001, 100002, 100003, 100004, 100005, 100006, 100007, 100008, 100009, 100010], 10);

    (new BulkPolicyDeleteJob($run->id))->handle($service);

    $run->refresh();
    expect($run->status)->toBe('aborted')
        ->and($run->failed)->toBe(6)
        ->and($run->processed_items)->toBe(6);
});

test('bulk export aborts when more than half of items fail', function () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create();

    $service = app(BulkOperationService::class);
    $run = $service->createRun($tenant, $user, 'policy', 'export', [200001, 200002, 200003, 200004, 200005, 200006, 200007, 200008, 200009, 200010], 10);

    (new BulkPolicyExportJob($run->id, 'Circuit Breaker Backup'))->handle($service);

    $run->refresh();
    expect($run->status)->toBe('aborted')
        ->and($run->failed)->toBe(6)
        ->and($run->processed_items)->toBe(6);

    $this->assertDatabaseHas('backup_sets', [
        'tenant_id' => $tenant->id,
        'name' => 'Circuit Breaker Backup',
        'status' => 'failed',
    ]);
});
