<?php

declare(strict_types=1);

use App\Services\EnvironmentReviews\EnvironmentReviewLifecycleService;
use App\Services\EnvironmentReviews\EnvironmentReviewReadinessGate;
use App\Support\EnvironmentReviewCompletenessState;
use App\Support\EnvironmentReviewStatus;
use App\Support\Ui\GovernanceArtifactTruth\ArtifactTruthPresenter;
use Tests\Feature\Concerns\BuildsGovernanceArtifactTruthFixtures;

uses(BuildsGovernanceArtifactTruthFixtures::class);

it('blocks publication when required review sections are missing from the anchored evidence basis', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $review = composeEnvironmentReviewForTest($tenant, $user, seedEnvironmentReviewEvidence(
        tenant: $tenant,
        permissionPayload: [
            'required_count' => 11,
            'granted_count' => 7,
        ],
        operationRunCount: 0,
    ));

    expect(app(EnvironmentReviewReadinessGate::class)->canPublish($review))->toBeFalse()
        ->and($review->publishBlockers())->not->toBeEmpty();

    $truth = app(ArtifactTruthPresenter::class)->forEnvironmentReview($review);

    expect($truth->artifactExistence)->toBe('created')
        ->and($truth->publicationReadiness)->toBe('blocked')
        ->and($truth->primaryLabel)->toBe('Publication blocked')
        ->and($truth->nextStepText())->toBe('Resolve the review blockers before publication');

    expect(fn () => app(EnvironmentReviewLifecycleService::class)->publish($review, $user, 'Ready for formal publication.'))
        ->toThrow(\InvalidArgumentException::class);
});

it('publishes ready environment reviews and archives them without mutating the published evidence history', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $review = $this->makeArtifactTruthReview(
        tenant: $tenant,
        user: $user,
        snapshot: $this->makeArtifactTruthEvidenceSnapshot($tenant),
        reviewOverrides: [
            'status' => EnvironmentReviewStatus::Ready->value,
            'completeness_state' => EnvironmentReviewCompletenessState::Complete->value,
        ],
        summaryOverrides: [
            'publish_blockers' => [],
            'section_state_counts' => [
                'complete' => 6,
                'partial' => 0,
                'missing' => 0,
                'stale' => 0,
            ],
        ],
    );

    $published = app(EnvironmentReviewLifecycleService::class)->publish($review, $user, 'Ready for formal publication.');
    $publishedAt = $published->published_at?->toIso8601String();

    expect($published->status)->toBe(EnvironmentReviewStatus::Published->value)
        ->and($published->published_by_user_id)->toBe((int) $user->getKey())
        ->and($publishedAt)->not->toBeNull();

    $publishedTruth = app(ArtifactTruthPresenter::class)->forEnvironmentReview($published);

    $archived = app(EnvironmentReviewLifecycleService::class)->archive($published, $user, 'Superseded by newer review cycle.');
    $archivedTruth = app(ArtifactTruthPresenter::class)->forEnvironmentReview($archived);

    expect($archived->status)->toBe(EnvironmentReviewStatus::Archived->value)
        ->and($archived->archived_at)->not->toBeNull()
        ->and($archived->published_at?->toIso8601String())->toBe($publishedAt)
        ->and($publishedTruth->publicationReadiness)->toBe('publishable')
        ->and($publishedTruth->nextStepText())->toBe('No action needed')
        ->and($archivedTruth->artifactExistence)->toBe('historical_only')
        ->and($archivedTruth->publicationReadiness)->toBe('internal_only')
        ->and($archivedTruth->nextStepText())->toBe('No action needed');
});

it('keeps stale published reviews internal only even when the lifecycle status is published', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $snapshot = seedStaleEnvironmentReviewEvidence($tenant);

    $review = $this->makeArtifactTruthReview(
        tenant: $tenant,
        user: $user,
        snapshot: $snapshot,
        reviewOverrides: [
            'status' => EnvironmentReviewStatus::Published->value,
            'published_at' => now(),
            'published_by_user_id' => (int) $user->getKey(),
            'completeness_state' => EnvironmentReviewCompletenessState::Complete->value,
        ],
        summaryOverrides: [
            'publish_blockers' => [],
            'section_state_counts' => [
                'complete' => 6,
                'partial' => 0,
                'missing' => 0,
                'stale' => 0,
            ],
        ],
    );

    $truth = app(ArtifactTruthPresenter::class)->forEnvironmentReview($review);

    expect($truth->freshnessState)->toBe('stale')
        ->and($truth->publicationReadiness)->toBe('internal_only')
        ->and($truth->primaryLabel)->toBe('Internal only')
        ->and($truth->nextStepText())->toBe('Refresh the evidence basis before publishing this review');
});

it('downgrades structurally ready reviews with partial evidence to internal only', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $snapshot = seedPartialEnvironmentReviewEvidence($tenant);

    $review = $this->makeArtifactTruthReview(
        tenant: $tenant,
        user: $user,
        snapshot: $snapshot,
        reviewOverrides: [
            'status' => EnvironmentReviewStatus::Ready->value,
            'completeness_state' => EnvironmentReviewCompletenessState::Complete->value,
        ],
        summaryOverrides: [
            'publish_blockers' => [],
            'section_state_counts' => [
                'complete' => 6,
                'partial' => 0,
                'missing' => 0,
                'stale' => 0,
            ],
        ],
    );

    $truth = app(ArtifactTruthPresenter::class)->forEnvironmentReview($review);

    expect($truth->contentState)->toBe('partial')
        ->and($truth->freshnessState)->toBe('current')
        ->and($truth->publicationReadiness)->toBe('internal_only')
        ->and($truth->primaryLabel)->toBe('Internal only')
        ->and($truth->nextStepText())->toBe('Complete the evidence basis before publishing this review');
});
