<?php

declare(strict_types=1);

use App\Filament\Pages\CrossTenantComparePage;
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 handoff from compare page into the operation viewer', function (): void {
    $fixture = $this->makeCrossTenantCompareFixture();

    $this->createPortfolioCompareSubject(
        tenant: $fixture['sourceTenant'],
        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(CrossTenantComparePage::getUrl(parameters: [
        'source_tenant_id' => (int) $fixture['sourceTenant']->getKey(),
        'target_tenant_id' => (int) $fixture['targetTenant']->getKey(),
        'policy_type' => ['deviceConfiguration'],
    ], panel: 'admin'));

    $page
        ->assertNoJavaScriptErrors()
        ->waitForText('Cross-tenant 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')
        ->assertSee('Open operation');

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

    $page
        ->click('Open operation')
        ->waitForText(OperationRunLinks::identifier((int) $run->getKey()))
        ->assertRoute('admin.operations.view', ['run' => (int) $run->getKey()])
        ->assertNoJavaScriptErrors()
        ->assertSee(OperationRunLinks::identifier((int) $run->getKey()));
});