<?php

declare(strict_types=1);

use App\Models\Finding;
use App\Models\User;
use App\Services\Findings\FindingExceptionService;
use App\Services\EnvironmentReviews\EnvironmentReviewComposer;
use App\Support\EnvironmentReviewCompletenessState;
use App\Support\EnvironmentReviewStatus;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('builds the first-slice environment review sections in a stable order', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $snapshot = seedEnvironmentReviewEvidence($tenant);

    $payload = app(EnvironmentReviewComposer::class)->compose($snapshot);

    expect(array_column($payload['sections'], 'section_key'))->toBe([
        'executive_summary',
        'control_interpretation',
        'open_risks',
        'accepted_risks',
        'permission_posture',
        'baseline_drift_posture',
        'operations_health',
    ])->and($payload['summary']['section_count'])->toBe(7)
        ->and($payload['summary']['control_interpretation']['version_key'] ?? null)->toBe('compliance_evidence_mapping.v1')
        ->and($payload['status'])->toBe(EnvironmentReviewStatus::Ready->value);
});

it('marks reviews as ready when evidence is partial but required sections are still present', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $snapshot = seedEnvironmentReviewEvidence($tenant, permissionPayload: [
        'required_count' => 12,
        'granted_count' => 9,
    ]);

    $payload = app(EnvironmentReviewComposer::class)->compose($snapshot);

    expect($payload['completeness_state'])->toBe(EnvironmentReviewCompletenessState::Partial->value)
        ->and($payload['status'])->toBe(EnvironmentReviewStatus::Ready->value)
        ->and($payload['summary']['publish_blockers'])->toBe([]);
});

it('derives a governance package summary from existing review and interpretation truth', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $snapshot = seedEnvironmentReviewEvidence($tenant);

    $payload = app(EnvironmentReviewComposer::class)->compose($snapshot);
    $package = $payload['summary']['governance_package'] ?? null;

    expect($package)->toBeArray()
        ->and($package['delivery_artifact_family'] ?? null)->toBe('review_pack')
        ->and($package['interpretation_version'] ?? null)->toBe('compliance_evidence_mapping.v1')
        ->and($package['executive_summary'] ?? null)->toBeString()
        ->and($package['top_findings'] ?? null)->toBeArray()
        ->and($package['evidence_basis_summary'] ?? null)->toBeString()
        ->and($package['accepted_risks'] ?? null)->toBeArray()
        ->and($package['governance_decisions'] ?? null)->toBeArray()
        ->and($package['supporting_artifact_links'] ?? null)->toBeArray();
});

it('keeps governance decision follow-up entries out of accepted risks', function (): void {
    [$requester, $tenant] = createUserWithTenant(role: 'owner');
    $approver = User::factory()->create();
    createUserWithTenant(tenant: $tenant, user: $approver, role: 'owner', workspaceRole: 'manager');

    /** @var FindingExceptionService $exceptionService */
    $exceptionService = app(FindingExceptionService::class);

    $validFinding = Finding::factory()->for($tenant)->create([
        'status' => Finding::STATUS_RISK_ACCEPTED,
    ]);

    $requested = $exceptionService->request($validFinding, $tenant, $requester, [
        'owner_user_id' => (int) $requester->getKey(),
        'request_reason' => 'Temporary exception while remediation is scheduled',
        'review_due_at' => now()->addDays(7)->toDateTimeString(),
        'expires_at' => now()->addDays(14)->toDateTimeString(),
    ]);

    $exceptionService->approve($requested, $approver, [
        'effective_from' => now()->subDay()->toDateTimeString(),
        'expires_at' => now()->addDays(14)->toDateTimeString(),
        'approval_reason' => 'Approved with controls',
    ]);

    $followUpFinding = Finding::factory()->for($tenant)->create([
        'status' => Finding::STATUS_RISK_ACCEPTED,
    ]);

    $snapshot = seedEnvironmentReviewEvidence($tenant, findingCount: 0, driftCount: 0);
    $package = app(EnvironmentReviewComposer::class)->compose($snapshot)['summary']['governance_package'] ?? [];

    expect(collect($package['accepted_risks'] ?? [])->pluck('finding_id')->all())
        ->toBe([(int) $validFinding->getKey()])
        ->and(collect($package['governance_decisions'] ?? [])->pluck('finding_id')->all())
        ->toBe([(int) $followUpFinding->getKey()]);
});
