<?php

declare(strict_types=1);

use App\Filament\Pages\CrossEnvironmentComparePage;
use App\Models\AuditLog;
use App\Models\OperationRun;
use App\Models\PolicyVersion;
use App\Support\Audit\AuditActionId;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\Feature\Concerns\BuildsPortfolioCompareFixtures;

uses(RefreshDatabase::class, BuildsPortfolioCompareFixtures::class);

it('audits promotion preflight generation without creating writes or operation runs', function (): void {
    $fixture = $this->makeCrossEnvironmentCompareFixture();

    $this->createPortfolioCompareSubject(
        tenant: $fixture['sourceEnvironment'],
        displayName: 'Audit Policy',
        snapshot: ['settings' => [['key' => 'audit', 'value' => 1]]],
    );
    $this->createPortfolioCompareSubject(
        tenant: $fixture['targetEnvironment'],
        displayName: 'Audit Policy',
        snapshot: ['settings' => [['key' => 'audit', 'value' => 2]]],
    );

    $this->setAdminWorkspaceContext($fixture['user'], $fixture['workspace']);

    $operationRunCount = OperationRun::query()->count();
    $policyVersionCount = PolicyVersion::query()->count();

    Livewire::withQueryParams([
        'source_environment_id' => (int) $fixture['sourceEnvironment']->getKey(),
        'target_environment_id' => (int) $fixture['targetEnvironment']->getKey(),
        'policy_type' => ['deviceConfiguration'],
    ])
        ->actingAs($fixture['user'])
        ->test(CrossEnvironmentComparePage::class)
        ->call('generatePromotionPreflight')
        ->assertHasNoErrors();

    $audit = AuditLog::query()
        ->where('workspace_id', (int) $fixture['workspace']->getKey())
        ->where('action', AuditActionId::CrossEnvironmentPromotionPreflightGenerated->value)
        ->latest('id')
        ->first();

    expect($audit)->not->toBeNull()
        ->and($audit?->status)->toBe('success')
        ->and($audit?->resource_type)->toBe('cross_environment_promotion_preflight')
        ->and(data_get($audit?->metadata, 'source_environment_id'))->toBe((int) $fixture['sourceEnvironment']->getKey())
        ->and(data_get($audit?->metadata, 'target_environment_id'))->toBe((int) $fixture['targetEnvironment']->getKey())
        ->and(data_get($audit?->metadata, 'ready_count'))->toBe(1)
        ->and(data_get($audit?->metadata, 'blocked_count'))->toBe(0)
        ->and(data_get($audit?->metadata, 'manual_mapping_required_count'))->toBe(0);

    expect(OperationRun::query()->count())->toBe($operationRunCount)
        ->and(PolicyVersion::query()->count())->toBe($policyVersionCount);
});