<?php

declare(strict_types=1);

use App\Models\Finding;
use App\Models\StoredReport;
use App\Models\User;
use App\Services\PermissionPosture\PermissionPostureFindingGenerator;
use App\Services\PermissionPosture\PostureResult;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

function buildComparison(array $permissions, string $overallStatus = 'missing'): array
{
    return [
        'overall_status' => $overallStatus,
        'permissions' => $permissions,
        'last_refreshed_at' => now()->toIso8601String(),
    ];
}

function missingPermission(string $key, array $features = ['policy-sync']): array
{
    return ['key' => $key, 'type' => 'application', 'status' => 'missing', 'features' => $features];
}

function grantedPermission(string $key, array $features = ['policy-sync']): array
{
    return ['key' => $key, 'type' => 'application', 'status' => 'granted', 'features' => $features];
}

function errorPermission(string $key, array $features = []): array
{
    return ['key' => $key, 'type' => 'application', 'status' => 'error', 'features' => $features];
}

// (1) Creates findings for missing permissions
it('creates findings for missing permissions with correct attributes', function (): void {
    [$user, $tenant] = createUserWithTenant();

    CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-02-24T10:00:00Z'));

    $generator = app(PermissionPostureFindingGenerator::class);
    $comparison = buildComparison([
        missingPermission('DeviceManagementApps.ReadWrite.All', ['policy-sync', 'backup']),
    ]);

    $result = $generator->generate($tenant, $comparison);

    expect($result)->toBeInstanceOf(PostureResult::class)
        ->and($result->findingsCreated)->toBe(1);

    $finding = Finding::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('finding_type', Finding::FINDING_TYPE_PERMISSION_POSTURE)
        ->first();

    expect($finding)->not->toBeNull()
        ->and($finding->source)->toBe('permission_check')
        ->and($finding->subject_type)->toBe('permission')
        ->and($finding->subject_external_id)->toBe('DeviceManagementApps.ReadWrite.All')
        ->and($finding->severity)->toBe(Finding::SEVERITY_HIGH) // 2 features → high
        ->and($finding->status)->toBe(Finding::STATUS_NEW)
        ->and($finding->first_seen_at?->toIso8601String())->toBe('2026-02-24T10:00:00+00:00')
        ->and($finding->last_seen_at?->toIso8601String())->toBe('2026-02-24T10:00:00+00:00')
        ->and($finding->times_seen)->toBe(1)
        ->and($finding->sla_days)->toBe(7)
        ->and($finding->due_at?->toIso8601String())->toBe('2026-03-03T10:00:00+00:00')
        ->and($finding->evidence_jsonb['permission_key'])->toBe('DeviceManagementApps.ReadWrite.All')
        ->and($finding->evidence_jsonb['actual_status'])->toBe('missing')
        ->and($finding->fingerprint)->not->toBeEmpty();

    CarbonImmutable::setTestNow();
});

// (2) Auto-resolves finding when permission granted
it('auto-resolves finding when permission is granted', function (): void {
    [$user, $tenant] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    // First run: missing
    $generator->generate($tenant, buildComparison([
        missingPermission('Perm.A'),
    ]));

    expect(Finding::query()->where('managed_environment_id', $tenant->getKey())->where('status', Finding::STATUS_NEW)->count())->toBe(1);

    // Second run: granted
    $result = $generator->generate($tenant, buildComparison([
        grantedPermission('Perm.A'),
    ], 'granted'));

    expect($result->findingsResolved)->toBe(1);

    $finding = Finding::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('finding_type', Finding::FINDING_TYPE_PERMISSION_POSTURE)
        ->first();

    expect($finding->status)->toBe(Finding::STATUS_RESOLVED)
        ->and($finding->resolved_at)->not->toBeNull()
        ->and($finding->resolved_reason)->toBe('permission_granted');
});

// (3) Auto-resolves triaged finding preserving triaged metadata
it('auto-resolves triaged finding preserving triaged metadata', function (): void {
    [$user, $tenant] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    $generator->generate($tenant, buildComparison([missingPermission('Perm.A')]));

    $finding = Finding::query()->where('managed_environment_id', $tenant->getKey())->first();
    $finding->forceFill([
        'status' => Finding::STATUS_TRIAGED,
        'triaged_at' => now(),
    ])->save();

    $result = $generator->generate($tenant, buildComparison([grantedPermission('Perm.A')], 'granted'));

    $finding->refresh();
    expect($result->findingsResolved)->toBe(1)
        ->and($finding->status)->toBe(Finding::STATUS_RESOLVED)
        ->and($finding->triaged_at)->not->toBeNull();
});

// (4) No duplicates on idempotent run
it('does not create duplicates on idempotent run', function (): void {
    [$user, $tenant] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-02-24T10:00:00Z'));
    $result1 = $generator->generate($tenant, buildComparison([missingPermission('Perm.A')]));

    CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-02-24T11:00:00Z'));
    $result2 = $generator->generate($tenant, buildComparison([missingPermission('Perm.A')]));

    expect($result1->findingsCreated)->toBe(1)
        ->and($result2->findingsCreated)->toBe(0)
        ->and($result2->findingsUnchanged)->toBe(1);

    expect(Finding::query()->where('managed_environment_id', $tenant->getKey())->count())->toBe(1);

    $finding = Finding::query()->where('managed_environment_id', $tenant->getKey())->first();
    expect($finding->times_seen)->toBe(2)
        ->and($finding->last_seen_at?->toIso8601String())->toBe('2026-02-24T11:00:00+00:00');

    CarbonImmutable::setTestNow();
});

it('repairs missing due-state fields on an existing open finding without extending the original due date', function (): void {
    [$user, $tenant] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-02-24T10:00:00Z'));
    $generator->generate($tenant, buildComparison([
        missingPermission('Perm.A', ['policy-sync', 'backup']),
    ]));

    $finding = Finding::query()->where('managed_environment_id', $tenant->getKey())->firstOrFail();
    $expectedDueAt = $finding->due_at?->toIso8601String();

    expect($finding->sla_days)->toBe(7)
        ->and($expectedDueAt)->toBe('2026-03-03T10:00:00+00:00');

    $finding->forceFill([
        'sla_days' => null,
        'due_at' => null,
    ])->save();

    CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-02-24T11:00:00Z'));
    $result = $generator->generate($tenant, buildComparison([
        missingPermission('Perm.A', ['policy-sync', 'backup']),
    ]));

    $finding->refresh();

    expect($result->findingsCreated)->toBe(0)
        ->and($result->findingsUnchanged)->toBe(1)
        ->and($finding->status)->toBe(Finding::STATUS_NEW)
        ->and($finding->first_seen_at?->toIso8601String())->toBe('2026-02-24T10:00:00+00:00')
        ->and($finding->last_seen_at?->toIso8601String())->toBe('2026-02-24T11:00:00+00:00')
        ->and($finding->times_seen)->toBe(2)
        ->and($finding->sla_days)->toBe(7)
        ->and($finding->due_at?->toIso8601String())->toBe($expectedDueAt);

    CarbonImmutable::setTestNow();
});

// (5) Re-opens resolved finding when permission revoked again
it('re-opens resolved finding when permission is revoked again', function (): void {
    [$user, $tenant] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    // Missing → resolve → missing again
    CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-02-24T10:00:00Z'));
    $generator->generate($tenant, buildComparison([missingPermission('Perm.A', ['policy-sync', 'backup'])]));

    $initial = Finding::query()->where('managed_environment_id', $tenant->getKey())->first();
    $initialDueAt = $initial->due_at;

    CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-02-25T10:00:00Z'));
    $generator->generate($tenant, buildComparison([grantedPermission('Perm.A')], 'granted'));

    $finding = Finding::query()->where('managed_environment_id', $tenant->getKey())->first();
    expect($finding->status)->toBe(Finding::STATUS_RESOLVED);

    CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-02-26T10:00:00Z'));
    $result = $generator->generate($tenant, buildComparison([missingPermission('Perm.A', ['policy-sync', 'backup'])]));

    $finding->refresh();
    expect($result->findingsReopened)->toBe(1)
        ->and($finding->status)->toBe(Finding::STATUS_REOPENED)
        ->and($finding->reopened_at?->toIso8601String())->toBe('2026-02-26T10:00:00+00:00')
        ->and($finding->resolved_at)->toBeNull()
        ->and($finding->resolved_reason)->toBeNull()
        ->and($finding->first_seen_at?->toIso8601String())->toBe('2026-02-24T10:00:00+00:00')
        ->and($finding->last_seen_at?->toIso8601String())->toBe('2026-02-26T10:00:00+00:00')
        ->and($finding->times_seen)->toBe(2)
        ->and($finding->sla_days)->toBe(7)
        ->and($finding->due_at?->toIso8601String())->toBe('2026-03-05T10:00:00+00:00')
        ->and($finding->due_at?->toIso8601String())->not->toBe($initialDueAt?->toIso8601String());

    CarbonImmutable::setTestNow();
});

// (6) Creates error finding for status=error permissions
it('creates error finding for status=error permissions', function (): void {
    [$user, $tenant] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    $result = $generator->generate($tenant, buildComparison([
        errorPermission('Perm.Error'),
    ]));

    expect($result->errorsRecorded)->toBe(1);

    $finding = Finding::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('finding_type', Finding::FINDING_TYPE_PERMISSION_POSTURE)
        ->first();

    expect($finding)->not->toBeNull()
        ->and($finding->severity)->toBe(Finding::SEVERITY_LOW)
        ->and($finding->evidence_jsonb['check_error'])->toBeTrue()
        ->and($finding->evidence_jsonb['actual_status'])->toBe('error');

    // Distinct fingerprint from missing findings
    $generator->generate($tenant, buildComparison([
        missingPermission('Perm.Error'),
    ]));

    expect(Finding::query()->where('managed_environment_id', $tenant->getKey())->count())->toBe(2);
});

// (7) Severity derivation
it('derives severity from feature count', function (int $featureCount, string $expectedSeverity): void {
    [$user, $tenant] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    $features = array_map(fn (int $i): string => "feature-$i", range(1, max(1, $featureCount)));
    if ($featureCount === 0) {
        $features = [];
    }

    $generator->generate($tenant, buildComparison([
        missingPermission('Perm.Sev', $features),
    ]));

    $finding = Finding::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('finding_type', Finding::FINDING_TYPE_PERMISSION_POSTURE)
        ->whereNull('resolved_at')
        ->first();

    expect($finding->severity)->toBe($expectedSeverity);
})->with([
    '0 features → low' => [0, Finding::SEVERITY_LOW],
    '1 feature → medium' => [1, Finding::SEVERITY_MEDIUM],
    '2 features → high' => [2, Finding::SEVERITY_HIGH],
    '3+ features → critical' => [3, Finding::SEVERITY_CRITICAL],
    '5 features → critical' => [5, Finding::SEVERITY_CRITICAL],
]);

// (8) Creates StoredReport with correct payload
it('creates StoredReport with correct payload', function (): void {
    [$user, $tenant] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    $comparison = buildComparison([
        grantedPermission('Perm.A', ['a', 'b']),
        missingPermission('Perm.B', ['c']),
    ]);

    $result = $generator->generate($tenant, $comparison);

    $report = StoredReport::query()->find($result->storedReportId);

    expect($report)->not->toBeNull()
        ->and($report->report_type)->toBe(StoredReport::REPORT_TYPE_PERMISSION_POSTURE)
        ->and($report->managed_environment_id)->toBe($tenant->getKey())
        ->and($report->payload['posture_score'])->toBe(50)
        ->and($report->payload['required_count'])->toBe(2)
        ->and($report->payload['granted_count'])->toBe(1)
        ->and($report->payload)->toHaveKey('checked_at')
        ->and($report->payload['permissions'])->toHaveCount(2);
});

// (9) No findings when all granted
it('resolves open findings when all permissions are granted', function (): void {
    [$user, $tenant] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    $generator->generate($tenant, buildComparison([missingPermission('Perm.A')]));
    expect(Finding::query()->where('managed_environment_id', $tenant->getKey())->where('status', Finding::STATUS_NEW)->count())->toBe(1);

    $result = $generator->generate($tenant, buildComparison([grantedPermission('Perm.A')], 'granted'));

    expect($result->findingsResolved)->toBe(1)
        ->and($result->findingsCreated)->toBe(0);
});

// (10) Produces alert events for new and reopened findings only
it('produces alert events for new and reopened findings only', function (): void {
    [$user, $tenant] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    // Run 1: create new finding → should produce alert event
    $generator->generate($tenant, buildComparison([missingPermission('Perm.A')]));
    $events = $generator->getAlertEvents();

    expect($events)->toHaveCount(1)
        ->and($events[0]['event_type'])->toBe('permission_missing');
});

// (11) Generator reads permissions from comparison, not hardcoded
it('processes arbitrary permission keys from comparison', function (): void {
    [$user, $tenant] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    $generator->generate($tenant, buildComparison([
        missingPermission('CustomPerm.ReadWrite.All', ['feature-x']),
    ]));

    $finding = Finding::query()->where('managed_environment_id', $tenant->getKey())->first();
    expect($finding->subject_external_id)->toBe('CustomPerm.ReadWrite.All');
});

// (12) All findings are scoped to managed_environment_id
it('scopes all findings to managed_environment_id', function (): void {
    [$user1, $tenant1] = createUserWithTenant();
    [$user2, $tenant2] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    $generator->generate($tenant1, buildComparison([missingPermission('Perm.A')]));
    $generator->generate($tenant2, buildComparison([missingPermission('Perm.A')]));

    expect(Finding::query()->where('managed_environment_id', $tenant1->getKey())->count())->toBe(1)
        ->and(Finding::query()->where('managed_environment_id', $tenant2->getKey())->count())->toBe(1);
});

// (13) subject_type and subject_external_id set correctly
it('sets subject_type=permission and subject_external_id on all posture findings', function (): void {
    [$user, $tenant] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    $generator->generate($tenant, buildComparison([
        missingPermission('DeviceManagementApps.ReadWrite.All'),
        missingPermission('DeviceManagementConfiguration.ReadWrite.All'),
    ]));

    $findings = Finding::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('finding_type', Finding::FINDING_TYPE_PERMISSION_POSTURE)
        ->get();

    foreach ($findings as $finding) {
        expect($finding->subject_type)->toBe('permission')
            ->and($finding->subject_external_id)->not->toBeEmpty();
    }
});

// (14) Stale findings auto-resolved for registry removals
it('auto-resolves stale findings for permissions removed from registry', function (): void {
    [$user, $tenant] = createUserWithTenant();
    $generator = app(PermissionPostureFindingGenerator::class);

    // Run 1: Perm.A and Perm.B are missing
    $generator->generate($tenant, buildComparison([
        missingPermission('Perm.A'),
        missingPermission('Perm.B'),
    ]));

    expect(Finding::query()->where('managed_environment_id', $tenant->getKey())->where('status', Finding::STATUS_NEW)->count())->toBe(2);

    // Run 2: Perm.B is no longer in the registry (only Perm.A remains)
    $result = $generator->generate($tenant, buildComparison([
        missingPermission('Perm.A'),
    ]));

    expect($result->findingsResolved)->toBeGreaterThanOrEqual(1);

    $stale = Finding::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('finding_type', Finding::FINDING_TYPE_PERMISSION_POSTURE)
        ->whereJsonContains('evidence_jsonb->permission_key', 'Perm.B')
        ->first();

    expect($stale->status)->toBe(Finding::STATUS_RESOLVED)
        ->and($stale->resolved_reason)->toBe('permission_removed_from_registry');
});
