<?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\ManagedEnvironment;
use App\Services\Evidence\EvidenceSnapshotService;
use App\Services\OperationRunService;
use App\Support\Evidence\EvidenceSnapshotStatus;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;

uses(RefreshDatabase::class);

function seedSnapshotInputs(ManagedEnvironment $tenant): void
{
    StoredReport::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'report_type' => StoredReport::REPORT_TYPE_PERMISSION_POSTURE,
        'fingerprint' => hash('sha256', 'perm-'.$tenant->getKey()),
    ]);
    StoredReport::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'report_type' => StoredReport::REPORT_TYPE_ENTRA_ADMIN_ROLES,
        'fingerprint' => hash('sha256', 'entra-'.$tenant->getKey()),
    ]);
    Finding::factory()->count(2)->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
    ]);
    Finding::factory()->create([
        'managed_environment_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('seeds and advances counted progress while evidence snapshot items are generated', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    seedSnapshotInputs($tenant);

    $service = app(EvidenceSnapshotService::class);
    $expectedItemCount = count($service->buildSnapshotPayload($tenant)['items']);
    $snapshot = $service->generate($tenant, $user);

    $seededCounts = [];
    $increments = [];
    $realOperationRuns = app(OperationRunService::class);

    $spyOperationRuns = new class($realOperationRuns, $seededCounts, $increments) extends OperationRunService
    {
        private array $seededCounts;

        private array $increments;

        public function __construct(private readonly OperationRunService $inner, array &$seededCounts, array &$increments)
        {
            $this->seededCounts = &$seededCounts;
            $this->increments = &$increments;
        }

        public function updateRun(OperationRun $run, string $status, ?string $outcome = null, array $summaryCounts = [], array $failures = []): OperationRun
        {
            if ($status === OperationRunStatus::Running->value && $summaryCounts !== []) {
                $this->seededCounts[] = $summaryCounts;
            }

            return $this->inner->updateRun($run, $status, $outcome, $summaryCounts, $failures);
        }

        public function incrementSummaryCounts(OperationRun $run, array $delta): OperationRun
        {
            $this->increments[] = $delta;

            return $this->inner->incrementSummaryCounts($run, $delta);
        }
    };

    $job = new GenerateEvidenceSnapshotJob(
        snapshotId: (int) $snapshot->getKey(),
        operationRunId: (int) $snapshot->operation_run_id,
    );

    $job->handle($service, $spyOperationRuns);

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

    expect($seededCounts)->toHaveCount(1)
        ->and($seededCounts[0])->toMatchArray([
            'total' => $expectedItemCount,
            'processed' => 0,
            'succeeded' => 0,
            'failed' => 0,
            'skipped' => 0,
        ])
        ->and($increments)->toHaveCount($expectedItemCount);

    foreach ($increments as $delta) {
        expect($delta)->toBe([
            'processed' => 1,
            'created' => 1,
        ]);
    }

    expect($snapshot->items)->toHaveCount($expectedItemCount)
        ->and($operationRun->summary_counts ?? [])->toMatchArray([
            'total' => $expectedItemCount,
            'processed' => $expectedItemCount,
            'created' => $expectedItemCount,
        ]);
});

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([
        'managed_environment_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);
});
