<?php

declare(strict_types=1);

use App\Jobs\GenerateEvidenceSnapshotJob;
use App\Models\EvidenceSnapshot;
use App\Models\Finding;
use App\Models\OperationRun;
use App\Models\StoredReport;
use App\Models\Tenant;
use App\Services\Evidence\EvidenceSnapshotService;
use App\Support\Evidence\EvidenceSnapshotStatus;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

function seedSnapshotInputs(Tenant $tenant): void
{
    StoredReport::factory()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'report_type' => StoredReport::REPORT_TYPE_PERMISSION_POSTURE,
        'fingerprint' => hash('sha256', 'perm-'.$tenant->getKey()),
    ]);
    StoredReport::factory()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'report_type' => StoredReport::REPORT_TYPE_ENTRA_ADMIN_ROLES,
        'fingerprint' => hash('sha256', 'entra-'.$tenant->getKey()),
    ]);
    Finding::factory()->count(2)->create([
        'tenant_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
    ]);
    Finding::factory()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'finding_type' => Finding::FINDING_TYPE_DRIFT,
    ]);
    OperationRun::factory()->forTenant($tenant)->create();
}

it('generates an active evidence snapshot from seeded inputs', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    seedSnapshotInputs($tenant);

    $snapshot = app(EvidenceSnapshotService::class)->generate($tenant, $user);

    $job = new GenerateEvidenceSnapshotJob(
        snapshotId: (int) $snapshot->getKey(),
        operationRunId: (int) $snapshot->operation_run_id,
    );
    app()->call([$job, 'handle']);

    $snapshot->refresh();
    $operationRun = OperationRun::query()->findOrFail($snapshot->operation_run_id);

    expect($snapshot->status)->toBe(EvidenceSnapshotStatus::Active->value)
        ->and($snapshot->items)->toHaveCount(5)
        ->and($snapshot->fingerprint)->toBeString()
        ->and($operationRun->status)->toBe(OperationRunStatus::Completed->value)
        ->and($operationRun->outcome)->toBe(OperationRunOutcome::Succeeded->value);
});

it('reuses an unchanged active snapshot fingerprint instead of creating a duplicate', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    seedSnapshotInputs($tenant);

    $first = app(EvidenceSnapshotService::class)->generate($tenant, $user);
    app()->call([new GenerateEvidenceSnapshotJob((int) $first->getKey(), (int) $first->operation_run_id), 'handle']);
    $first->refresh();

    $second = app(EvidenceSnapshotService::class)->generate($tenant, $user);

    expect((int) $second->getKey())->toBe((int) $first->getKey())
        ->and(EvidenceSnapshot::query()->count())->toBe(1);
});

it('supersedes the previous active snapshot when the evidence fingerprint changes', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    seedSnapshotInputs($tenant);

    $first = app(EvidenceSnapshotService::class)->generate($tenant, $user);
    app()->call([new GenerateEvidenceSnapshotJob((int) $first->getKey(), (int) $first->operation_run_id), 'handle']);
    $first->refresh();

    Finding::factory()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'fingerprint' => Str::random(64),
    ]);

    $second = app(EvidenceSnapshotService::class)->generate($tenant, $user);
    app()->call([new GenerateEvidenceSnapshotJob((int) $second->getKey(), (int) $second->operation_run_id), 'handle']);

    $first->refresh();
    $second->refresh();

    expect($first->status)->toBe(EvidenceSnapshotStatus::Superseded->value)
        ->and($second->status)->toBe(EvidenceSnapshotStatus::Active->value)
        ->and((string) $first->fingerprint)->not->toBe((string) $second->fingerprint);
});
