<?php

declare(strict_types=1);

use App\Filament\Pages\CrossTenantComparePage;
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->makeCrossTenantCompareFixture();

    $this->createPortfolioCompareSubject(
        tenant: $fixture['sourceTenant'],
        displayName: 'Audit Policy',
        snapshot: ['settings' => [['key' => 'audit', 'value' => 1]]],
    );
    $this->createPortfolioCompareSubject(
        tenant: $fixture['targetTenant'],
        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_tenant_id' => (int) $fixture['sourceTenant']->getKey(),
        'target_tenant_id' => (int) $fixture['targetTenant']->getKey(),
        'policy_type' => ['deviceConfiguration'],
    ])
        ->actingAs($fixture['user'])
        ->test(CrossTenantComparePage::class)
        ->call('generatePromotionPreflight')
        ->assertHasNoErrors();

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

    expect($audit)->not->toBeNull()
        ->and($audit?->status)->toBe('success')
        ->and($audit?->resource_type)->toBe('cross_tenant_promotion_preflight')
        ->and(data_get($audit?->metadata, 'source_tenant_id'))->toBe((int) $fixture['sourceTenant']->getKey())
        ->and(data_get($audit?->metadata, 'target_tenant_id'))->toBe((int) $fixture['targetTenant']->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);
});