<?php

declare(strict_types=1);

use App\Models\BaselineProfile;
use App\Models\BaselineSnapshot;
use App\Models\BaselineTenantAssignment;
use App\Models\Finding;
use App\Models\FindingException;
use App\Models\OperationRun;
use App\Support\Baselines\BaselineCompareReasonCode;
use App\Support\Baselines\BaselineCompareStats;
use App\Support\Baselines\BaselineCompareSummaryAssessment;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;

function createAssignedBaselineTenant(): array
{
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $profile = BaselineProfile::factory()->active()->create([
        'workspace_id' => (int) $tenant->workspace_id,
    ]);

    $snapshot = BaselineSnapshot::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'baseline_profile_id' => (int) $profile->getKey(),
    ]);

    $profile->update(['active_snapshot_id' => (int) $snapshot->getKey()]);

    BaselineTenantAssignment::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'baseline_profile_id' => (int) $profile->getKey(),
    ]);

    return [$tenant, $profile, $snapshot];
}

it('marks trustworthy no-drift results as positive and eligible for an aligned claim', function (): void {
    [$tenant, $profile, $snapshot] = createAssignedBaselineTenant();

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Succeeded->value,
        'completed_at' => now(),
        'context' => [
            'baseline_profile_id' => (int) $profile->getKey(),
            'baseline_snapshot_id' => (int) $snapshot->getKey(),
            'baseline_compare' => [
                'reason_code' => BaselineCompareReasonCode::NoDriftDetected->value,
                'coverage' => [
                    'effective_types' => ['deviceConfiguration'],
                    'covered_types' => ['deviceConfiguration'],
                    'uncovered_types' => [],
                    'proof' => true,
                ],
            ],
        ],
    ]);

    $assessment = BaselineCompareStats::forTenant($tenant)->summaryAssessment();

    expect($assessment->stateFamily)->toBe(BaselineCompareSummaryAssessment::STATE_POSITIVE)
        ->and($assessment->positiveClaimAllowed)->toBeTrue()
        ->and($assessment->evaluationResult)->toBe('no_result')
        ->and($assessment->headline)->toBe('No confirmed drift in the latest baseline compare.');
});

it('keeps limited-confidence zero findings in a cautionary state', function (): void {
    [$tenant, $profile, $snapshot] = createAssignedBaselineTenant();

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::PartiallySucceeded->value,
        'completed_at' => now(),
        'context' => [
            'baseline_profile_id' => (int) $profile->getKey(),
            'baseline_snapshot_id' => (int) $snapshot->getKey(),
            'baseline_compare' => [
                'reason_code' => BaselineCompareReasonCode::CoverageUnproven->value,
                'coverage' => [
                    'effective_types' => ['deviceConfiguration', 'deviceCompliancePolicy'],
                    'covered_types' => ['deviceConfiguration'],
                    'uncovered_types' => ['deviceCompliancePolicy'],
                    'proof' => false,
                ],
            ],
        ],
    ]);

    $assessment = BaselineCompareStats::forTenant($tenant)->summaryAssessment();

    expect($assessment->stateFamily)->toBe(BaselineCompareSummaryAssessment::STATE_CAUTION)
        ->and($assessment->positiveClaimAllowed)->toBeFalse()
        ->and($assessment->evaluationResult)->toBe('suppressed_result')
        ->and($assessment->nextActionTarget())->toBe(BaselineCompareSummaryAssessment::NEXT_TARGET_RUN);
});

it('treats failed compare runs as action required with a failed-result semantic', function (): void {
    [$tenant, $profile, $snapshot] = createAssignedBaselineTenant();

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Failed->value,
        'completed_at' => now(),
        'context' => [
            'baseline_profile_id' => (int) $profile->getKey(),
            'baseline_snapshot_id' => (int) $snapshot->getKey(),
        ],
    ]);

    $assessment = BaselineCompareStats::forTenant($tenant)->summaryAssessment();

    expect($assessment->stateFamily)->toBe(BaselineCompareSummaryAssessment::STATE_ACTION_REQUIRED)
        ->and($assessment->evaluationResult)->toBe('failed_result')
        ->and($assessment->nextActionLabel())->toBe('Review the failed operation');
});

it('treats stale compare history as a stale summary state instead of positive', function (): void {
    [$tenant, $profile, $snapshot] = createAssignedBaselineTenant();

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Succeeded->value,
        'completed_at' => now()->subDays(9),
        'context' => [
            'baseline_profile_id' => (int) $profile->getKey(),
            'baseline_snapshot_id' => (int) $snapshot->getKey(),
            'baseline_compare' => [
                'reason_code' => BaselineCompareReasonCode::NoDriftDetected->value,
                'coverage' => [
                    'effective_types' => ['deviceConfiguration'],
                    'covered_types' => ['deviceConfiguration'],
                    'uncovered_types' => [],
                    'proof' => true,
                ],
            ],
        ],
    ]);

    $assessment = BaselineCompareStats::forTenant($tenant)->summaryAssessment();

    expect($assessment->stateFamily)->toBe(BaselineCompareSummaryAssessment::STATE_STALE)
        ->and($assessment->positiveClaimAllowed)->toBeFalse()
        ->and($assessment->evidenceImpact)->toBe(BaselineCompareSummaryAssessment::EVIDENCE_STALE_RESULT);
});

it('keeps open findings action-required even when compare evidence is otherwise usable', function (): void {
    [$tenant, $profile, $snapshot] = createAssignedBaselineTenant();

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Succeeded->value,
        'completed_at' => now(),
        'context' => [
            'baseline_profile_id' => (int) $profile->getKey(),
            'baseline_snapshot_id' => (int) $snapshot->getKey(),
            'baseline_compare' => [
                'coverage' => [
                    'effective_types' => ['deviceConfiguration'],
                    'covered_types' => ['deviceConfiguration'],
                    'uncovered_types' => [],
                    'proof' => true,
                ],
            ],
        ],
    ]);

    Finding::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'finding_type' => Finding::FINDING_TYPE_DRIFT,
        'source' => 'baseline.compare',
        'scope_key' => 'baseline_profile:'.$profile->getKey(),
        'severity' => Finding::SEVERITY_HIGH,
        'status' => Finding::STATUS_NEW,
    ]);

    $assessment = BaselineCompareStats::forTenant($tenant)->summaryAssessment();

    expect($assessment->stateFamily)->toBe(BaselineCompareSummaryAssessment::STATE_ACTION_REQUIRED)
        ->and($assessment->findingsVisibleCount)->toBe(1)
        ->and($assessment->nextActionTarget())->toBe(BaselineCompareSummaryAssessment::NEXT_TARGET_FINDINGS);
});

it('treats overdue workflow and lapsed governance as action required even with zero compare findings', function (): void {
    [$tenant, $profile, $snapshot] = createAssignedBaselineTenant();

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Succeeded->value,
        'completed_at' => now(),
        'context' => [
            'baseline_profile_id' => (int) $profile->getKey(),
            'baseline_snapshot_id' => (int) $snapshot->getKey(),
            'baseline_compare' => [
                'reason_code' => BaselineCompareReasonCode::NoDriftDetected->value,
                'coverage' => [
                    'effective_types' => ['deviceConfiguration'],
                    'covered_types' => ['deviceConfiguration'],
                    'uncovered_types' => [],
                    'proof' => true,
                ],
            ],
        ],
    ]);

    Finding::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'status' => Finding::STATUS_TRIAGED,
        'due_at' => now()->subDay(),
    ]);

    Finding::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'status' => Finding::STATUS_RISK_ACCEPTED,
    ]);

    $assessment = BaselineCompareStats::forTenant($tenant)->summaryAssessment();

    expect($assessment->stateFamily)->toBe(BaselineCompareSummaryAssessment::STATE_ACTION_REQUIRED)
        ->and($assessment->overdueOpenFindingsCount)->toBe(1)
        ->and($assessment->lapsedGovernanceCount)->toBe(1)
        ->and($assessment->headline)->toContain('Accepted-risk governance has lapsed')
        ->and($assessment->nextActionTarget())->toBe(BaselineCompareSummaryAssessment::NEXT_TARGET_FINDINGS);
});

it('maps unavailable compare prerequisites to baseline prerequisite guidance', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $profile = BaselineProfile::factory()->active()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'active_snapshot_id' => null,
    ]);

    BaselineTenantAssignment::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'baseline_profile_id' => (int) $profile->getKey(),
    ]);

    $assessment = BaselineCompareStats::forTenant($tenant)->summaryAssessment();

    expect($assessment->stateFamily)->toBe(BaselineCompareSummaryAssessment::STATE_UNAVAILABLE)
        ->and($assessment->headline)->toBe('The current baseline snapshot is not available for compare.')
        ->and($assessment->nextActionLabel())->toBe('Review baseline prerequisites')
        ->and($assessment->nextActionTarget())->toBe(BaselineCompareSummaryAssessment::NEXT_TARGET_LANDING);
});

it('treats expiring governance as action required even with zero compare findings', function (): void {
    [$tenant, $profile, $snapshot] = createAssignedBaselineTenant();
    [$user] = createUserWithTenant(tenant: $tenant, role: 'owner');

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Succeeded->value,
        'completed_at' => now(),
        'context' => [
            'baseline_profile_id' => (int) $profile->getKey(),
            'baseline_snapshot_id' => (int) $snapshot->getKey(),
            'baseline_compare' => [
                'reason_code' => BaselineCompareReasonCode::NoDriftDetected->value,
                'coverage' => [
                    'effective_types' => ['deviceConfiguration'],
                    'covered_types' => ['deviceConfiguration'],
                    'uncovered_types' => [],
                    'proof' => true,
                ],
            ],
        ],
    ]);

    $finding = Finding::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'status' => Finding::STATUS_RISK_ACCEPTED,
    ]);

    FindingException::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'finding_id' => (int) $finding->getKey(),
        'requested_by_user_id' => (int) $user->getKey(),
        'owner_user_id' => (int) $user->getKey(),
        'approved_by_user_id' => (int) $user->getKey(),
        'status' => FindingException::STATUS_EXPIRING,
        'current_validity_state' => FindingException::VALIDITY_EXPIRING,
        'request_reason' => 'Expiring governance coverage',
        'approval_reason' => 'Approved for coverage',
        'requested_at' => now()->subDays(2),
        'approved_at' => now()->subDay(),
        'effective_from' => now()->subDay(),
        'expires_at' => now()->addDays(2),
        'review_due_at' => now()->addDay(),
        'evidence_summary' => ['reference_count' => 0],
    ]);

    $assessment = BaselineCompareStats::forTenant($tenant)->summaryAssessment();

    expect($assessment->stateFamily)->toBe(BaselineCompareSummaryAssessment::STATE_ACTION_REQUIRED)
        ->and($assessment->expiringGovernanceCount)->toBe(1)
        ->and($assessment->headline)->toContain('Accepted-risk governance is nearing expiry')
        ->and($assessment->nextActionLabel())->toBe('Open findings');
});
