<?php

declare(strict_types=1);

use App\Jobs\BulkPolicyVersionForceDeleteJob;
use App\Jobs\Operations\PolicyVersionForceDeleteWorkerJob;
use App\Models\OperationRun;
use App\Models\Policy;
use App\Models\PolicyVersion;
use App\Services\OperationRunService;
use App\Services\Operations\TargetScopeConcurrencyLimiter;
use Illuminate\Contracts\Cache\Lock;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Cache;

it('dispatches policy version force delete workers and sets total', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $run = OperationRun::factory()->create([
        'tenant_id' => $tenant->id,
        'user_id' => $user->id,
        'type' => 'policy_version.force_delete',
        'status' => 'queued',
        'summary_counts' => [],
        'context' => [
            'target_scope' => [
                'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id),
            ],
        ],
    ]);

    Bus::fake();

    $job = new BulkPolicyVersionForceDeleteJob(
        tenantId: (int) $tenant->getKey(),
        userId: (int) $user->getKey(),
        policyVersionIds: [3, 2, 1],
        operationRun: $run,
        context: [],
    );

    $job->handle(app(OperationRunService::class));

    $run = $run->fresh();

    expect($run)->not->toBeNull();
    expect($run?->status)->toBe('running');
    expect($run?->summary_counts['total'] ?? null)->toBe(3);

    Bus::assertDispatched(PolicyVersionForceDeleteWorkerJob::class, 3);
})->group('ops-ux');

it('force deletes only archived versions and updates summary counts', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $policy = Policy::factory()->create([
        'tenant_id' => $tenant->id,
    ]);

    $archived = PolicyVersion::factory()->create([
        'tenant_id' => $tenant->id,
        'policy_id' => $policy->id,
        'version_number' => 1,
        'deleted_at' => now(),
    ]);

    $active = PolicyVersion::factory()->create([
        'tenant_id' => $tenant->id,
        'policy_id' => $policy->id,
        'version_number' => 2,
        'deleted_at' => null,
    ]);

    $run = OperationRun::factory()->create([
        'tenant_id' => $tenant->id,
        'user_id' => $user->id,
        'type' => 'policy_version.force_delete',
        'status' => 'running',
        'summary_counts' => [
            'total' => 2,
            'processed' => 0,
            'failed' => 0,
        ],
        'context' => [
            'target_scope' => [
                'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id),
            ],
        ],
    ]);

    $lock = new class implements Lock
    {
        public function get($callback = null): bool
        {
            return true;
        }

        public function block($seconds, $callback = null): bool
        {
            return true;
        }

        public function release(): bool
        {
            return true;
        }

        public function owner(): string
        {
            return 'test';
        }

        public function forceRelease(): void
        {
            // no-op
        }
    };

    Cache::partialMock()
        ->shouldReceive('lock')
        ->andReturn($lock);

    (new PolicyVersionForceDeleteWorkerJob(
        tenantId: (int) $tenant->getKey(),
        userId: (int) $user->getKey(),
        policyVersionId: (int) $archived->getKey(),
        operationRun: $run,
    ))->handle(app(OperationRunService::class), app(TargetScopeConcurrencyLimiter::class));

    (new PolicyVersionForceDeleteWorkerJob(
        tenantId: (int) $tenant->getKey(),
        userId: (int) $user->getKey(),
        policyVersionId: (int) $active->getKey(),
        operationRun: $run,
    ))->handle(app(OperationRunService::class), app(TargetScopeConcurrencyLimiter::class));

    $run = $run->fresh();

    expect(PolicyVersion::withTrashed()->whereKey($archived->getKey())->exists())->toBeFalse();
    expect(PolicyVersion::withTrashed()->whereKey($active->getKey())->exists())->toBeTrue();

    expect($run)->not->toBeNull();
    expect($run?->status)->toBe('completed');
    expect($run?->outcome)->toBe('succeeded');

    expect($run?->summary_counts['processed'] ?? null)->toBe(2);
    expect($run?->summary_counts['succeeded'] ?? null)->toBe(1);
    expect($run?->summary_counts['deleted'] ?? null)->toBe(1);
    expect($run?->summary_counts['skipped'] ?? null)->toBe(1);
})->group('ops-ux');
