<?php

declare(strict_types=1);

use App\Filament\Pages\CrossEnvironmentComparePage;
use App\Models\OperationRun;
use App\Support\OperationRunLinks;
use App\Support\Workspaces\WorkspaceContext;
use Tests\Feature\Concerns\BuildsPortfolioCompareFixtures;

uses(BuildsPortfolioCompareFixtures::class);

pest()->browser()->timeout(15_000);

it('smokes queued promotion execution and the canonical operation viewer', function (): void {
    $fixture = $this->makeCrossEnvironmentCompareFixture();

    $this->createPortfolioCompareSubject(
        tenant: $fixture['sourceEnvironment'],
        displayName: 'Browser Promotion Policy',
        snapshot: ['settings' => [['key' => 'browser', 'value' => 1]]],
    );

    $this->actingAs($fixture['user'])->withSession([
        WorkspaceContext::SESSION_KEY => (int) $fixture['workspace']->getKey(),
    ]);
    session()->put(WorkspaceContext::SESSION_KEY, (int) $fixture['workspace']->getKey());

    $page = visit(CrossEnvironmentComparePage::getUrl(parameters: [
        'source_environment_id' => (int) $fixture['sourceEnvironment']->getKey(),
        'target_environment_id' => (int) $fixture['targetEnvironment']->getKey(),
        'policy_type' => ['deviceConfiguration'],
    ], panel: 'admin'));

    $page
        ->assertNoJavaScriptErrors()
        ->waitForText('Cross-environment compare')
        ->assertSee('Compare preview')
        ->click('Generate promotion preflight')
        ->waitForText('Promotion preflight')
        ->assertSee('Execute promotion')
        ->click('Execute promotion')
        ->waitForText('Queue promotion')
        ->click('Queue promotion')
        ->waitForText('Promotion execution queued');

    $run = OperationRun::query()->latest('id')->firstOrFail();

    visit(OperationRunLinks::tenantlessView($run))
        ->waitForText(OperationRunLinks::identifier((int) $run->getKey()))
        ->assertRoute('admin.operations.view', [
            'workspace' => (int) $run->workspace_id,
            'run' => (int) $run->getKey(),
        ])
        ->assertNoJavaScriptErrors()
        ->assertSee(OperationRunLinks::identifier((int) $run->getKey()));
});
