<?php

declare(strict_types=1);

use App\Models\AuditLog;
use App\Models\Finding;
use App\Models\ManagedEnvironment;
use App\Services\Audit\AuditRecorder;
use App\Services\Findings\FindingWorkflowService;
use App\Support\Audit\AuditActionId;
use App\Support\Audit\AuditActorSnapshot;
use App\Support\Audit\AuditActorType;
use App\Support\Audit\AuditTargetSnapshot;

it('writes exactly one canonical audit row per successful workflow mutation', function (): void {
    [$user, $tenant] = $this->actingAsFindingOperator('owner');

    $service = app(FindingWorkflowService::class);
    $finding = $this->makeFindingForWorkflow($tenant, Finding::STATUS_NEW);

    $service->triage($finding, $tenant, $user);
    $service->assign($finding->refresh(), $tenant, $user, null, (int) $user->getKey());
    $service->resolve($finding->refresh(), $tenant, $user, Finding::RESOLVE_REASON_REMEDIATED);
    $service->reopen($finding->refresh(), $tenant, $user, Finding::REOPEN_REASON_MANUAL_REASSESSMENT);
    $service->close($finding->refresh(), $tenant, $user, Finding::CLOSE_REASON_DUPLICATE);

    expect(AuditLog::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('resource_type', 'finding')
        ->where('resource_id', (string) $finding->getKey())
        ->count())->toBe(5);

    $closedAudit = $this->latestFindingAudit($finding, AuditActionId::FindingClosed);

    expect($closedAudit)->not->toBeNull();
    expect($closedAudit->actorSnapshot()->type)->toBe(AuditActorType::Human)
        ->and($closedAudit->targetDisplayLabel())->toContain('finding')
        ->and(data_get($closedAudit->metadata, 'before_status'))->toBe(Finding::STATUS_REOPENED)
        ->and(data_get($closedAudit->metadata, 'after_status'))->toBe(Finding::STATUS_CLOSED)
        ->and(data_get($closedAudit->metadata, 'closed_reason'))->toBe(Finding::CLOSE_REASON_DUPLICATE)
        ->and(data_get($closedAudit->metadata, 'before.evidence_jsonb'))->toBeNull()
        ->and(data_get($closedAudit->metadata, 'after.evidence_jsonb'))->toBeNull();

    $reopenedAudit = $this->latestFindingAudit($finding, AuditActionId::FindingReopened);

    expect($reopenedAudit)->not->toBeNull()
        ->and(data_get($reopenedAudit->metadata, 'reopened_reason'))->toBe(Finding::REOPEN_REASON_MANUAL_REASSESSMENT);
});

it('deduplicates repeated finding audit writes for the same successful mutation payload', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    $finding = Finding::factory()->for($tenant)->resolved()->create();

    $recorder = app(AuditRecorder::class);

    $payload = [
        'metadata' => [
            'finding_id' => (int) $finding->getKey(),
            'before_status' => Finding::STATUS_TRIAGED,
            'after_status' => Finding::STATUS_RESOLVED,
            'before' => ['status' => Finding::STATUS_TRIAGED],
            'after' => ['status' => Finding::STATUS_RESOLVED],
            '_dedupe_key' => 'finding-resolved-'.$finding->getKey(),
        ],
    ];

    $first = $recorder->record(
        action: AuditActionId::FindingResolved,
        context: $payload,
        workspace: $tenant->workspace,
        tenant: $tenant,
        actor: AuditActorSnapshot::fromLegacy(AuditActorType::Human, 1, 'owner@example.com', 'Owner'),
        target: new AuditTargetSnapshot(type: 'finding', id: (string) $finding->getKey(), label: 'Permission posture finding #'.$finding->getKey()),
        outcome: 'success',
    );

    $second = $recorder->record(
        action: AuditActionId::FindingResolved,
        context: $payload,
        workspace: $tenant->workspace,
        tenant: $tenant,
        actor: AuditActorSnapshot::fromLegacy(AuditActorType::Human, 1, 'owner@example.com', 'Owner'),
        target: new AuditTargetSnapshot(type: 'finding', id: (string) $finding->getKey(), label: 'Permission posture finding #'.$finding->getKey()),
        outcome: 'success',
    );

    expect((int) $first->getKey())->toBe((int) $second->getKey())
        ->and(AuditLog::query()
            ->where('managed_environment_id', (int) $tenant->getKey())
            ->where('action', AuditActionId::FindingResolved->value)
            ->where('resource_type', 'finding')
            ->where('resource_id', (string) $finding->getKey())
            ->count())->toBe(1);
});

it('stores system-origin audit metadata without raw evidence payloads', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    $finding = Finding::factory()->for($tenant)->resolved()->create([
        'evidence_jsonb' => [
            'secret' => 'should-never-appear',
            'payload' => ['a' => 'b'],
        ],
    ]);

    $audit = app(AuditRecorder::class)->record(
        action: AuditActionId::FindingReopened,
        context: [
            'metadata' => [
                'finding_id' => (int) $finding->getKey(),
                'before_status' => Finding::STATUS_RESOLVED,
                'after_status' => Finding::STATUS_REOPENED,
                'before' => [
                    'status' => Finding::STATUS_RESOLVED,
                    'evidence_jsonb' => ['secret' => 'leak'],
                ],
                'after' => [
                    'status' => Finding::STATUS_REOPENED,
                    'evidence_jsonb' => ['secret' => 'leak'],
                ],
                'system_origin' => true,
                '_actor_type' => AuditActorType::System->value,
            ],
        ],
        workspace: $tenant->workspace,
        tenant: $tenant,
        actor: AuditActorSnapshot::fromLegacy(AuditActorType::System),
        target: new AuditTargetSnapshot(type: 'finding', id: (string) $finding->getKey(), label: 'Drift finding #'.$finding->getKey()),
        outcome: 'success',
    );

    expect($audit->actorSnapshot()->type)->toBe(AuditActorType::System)
        ->and(data_get($audit->metadata, 'system_origin'))->toBeTrue()
        ->and(data_get($audit->metadata, 'before.evidence_jsonb'))->toBeNull()
        ->and(data_get($audit->metadata, 'after.evidence_jsonb'))->toBeNull();
});
