<?php

declare(strict_types=1);

use App\Filament\Pages\Monitoring\Operations;
use App\Models\ManagedEnvironment;
use App\Models\OperationRun;
use App\Support\Navigation\CanonicalNavigationContext;
use App\Support\OperationRunLinks;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Route;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('serves /admin/operations without tenant context (workspace-wide)', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    [$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner');

    $tenantB = ManagedEnvironment::factory()->create([
        'status' => 'active',
        'workspace_id' => (int) $tenantA->workspace_id,
    ]);

    $user->tenants()->syncWithoutDetaching([
        $tenantB->getKey() => ['role' => 'owner'],
    ]);

    $runA = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenantA->getKey(),
        'workspace_id' => (int) $tenantA->workspace_id,
        'type' => 'policy.sync',
        'initiator_name' => 'TenantA',
    ]);

    $runB = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenantB->getKey(),
        'workspace_id' => (int) $tenantB->workspace_id,
        'type' => 'inventory_sync',
        'initiator_name' => 'TenantB',
    ]);

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id])
        ->get(\App\Support\OperationRunLinks::index())
        ->assertOk()
        ->assertSee('Policy sync')
        ->assertSee('Inventory sync')
        ->assertSee('TenantA')
        ->assertSee('TenantB');
});

it('serves /admin/operations/{run} with and without tenant context', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant($tenant, role: 'owner');

    $run = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => 'policy.sync',
    ]);

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(\App\Support\OperationRunLinks::tenantlessView($run))
        ->assertOk()
        ->assertSee(OperationRunLinks::identifier($run))
        ->assertDontSee('/admin/t/'.((int) $tenant->getKey()).'/operations/r/'.((int) $run->getKey()));

    Filament::setTenant($tenant, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(\App\Support\OperationRunLinks::tenantlessView($run))
        ->assertOk()
        ->assertSee(OperationRunLinks::identifier($run));
});

it('keeps operation detail accessible when the active tenant context does not match the run tenant', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    [$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');

    $tenantB = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $tenantA->workspace_id,
    ]);

    createUserWithTenant(tenant: $tenantB, user: $user, role: 'owner');

    $runB = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenantB->getKey(),
        'workspace_id' => (int) $tenantB->workspace_id,
        'type' => 'inventory_sync',
    ]);

    setAdminPanelContext($tenantA);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id])
        ->get(\App\Support\OperationRunLinks::tenantlessView($runB))
        ->assertOk()
        ->assertSee(OperationRunLinks::identifier($runB));
});

it('keeps canonical operation detail accessible for selector-excluded tenant runs', function (): void {
    $tenant = ManagedEnvironment::factory()->create([
        'status' => ManagedEnvironment::STATUS_ONBOARDING,
    ]);
    [$user, $tenant] = createUserWithTenant($tenant, role: 'owner');

    $run = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => 'provider.connection.check',
    ]);

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(\App\Support\OperationRunLinks::tenantlessView($run))
        ->assertOk()
        ->assertSee('Operation environment is not available in the current environment selector')
        ->assertSee('This tenant is currently onboarding');
});

it('keeps tenant context out of the operations filter unless an explicit page query is present', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    [$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner');

    $tenantB = ManagedEnvironment::factory()->create([
        'status' => 'active',
        'workspace_id' => (int) $tenantA->workspace_id,
    ]);

    $user->tenants()->syncWithoutDetaching([
        $tenantB->getKey() => ['role' => 'owner'],
    ]);

    $runA = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenantA->getKey(),
        'workspace_id' => (int) $tenantA->workspace_id,
        'type' => 'policy.sync',
        'initiator_name' => 'TenantA',
    ]);

    $runB = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenantB->getKey(),
        'workspace_id' => (int) $tenantB->workspace_id,
        'type' => 'inventory_sync',
        'initiator_name' => 'TenantB',
    ]);

    setAdminPanelContext($tenantA);

    $this->withSession([
        WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id,
    ]);
    session([
        WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id,
    ]);

    Livewire::withHeaders(['referer' => route('admin.operations.index', ['workspace' => $tenantA->workspace])])
        ->actingAs($user)
        ->test(Operations::class)
        ->assertCanSeeTableRecords([$runA, $runB])
        ->assertSet('tableFilters.managed_environment_id.value', null);

    Livewire::withHeaders(['referer' => route('admin.operations.index', ['workspace' => $tenantA->workspace])])
        ->withQueryParams(['environment_id' => (int) $tenantA->getKey()])
        ->test(Operations::class)
        ->assertCanSeeTableRecords([$runA])
        ->assertCanNotSeeTableRecords([$runB])
        ->assertSet('tableFilters.managed_environment_id.value', (string) $tenantA->getKey());
});

it('shows an explicit back-link when canonical context is present on the operations index', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant($tenant, role: 'owner');

    Filament::setTenant($tenant, true);

    $context = new CanonicalNavigationContext(
        sourceSurface: 'backup_set.detail_section',
        canonicalRouteName: 'admin.operations.index',
        tenantId: (int) $tenant->getKey(),
        backLinkLabel: 'Back to backup set',
        backLinkUrl: '/admin/tenant/backup-sets/1',
    );

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(OperationRunLinks::index($tenant, $context))
        ->assertOk()
        ->assertSee('Monitoring landing')
        ->assertSee('Return path')
        ->assertSee('Back to backup set')
        ->assertSee('/admin/tenant/backup-sets/1', false);
});

it('keeps the canonical back-link action after Livewire hydration on the operations index', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant($tenant, role: 'owner');

    Filament::setTenant($tenant, true);

    $this->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]);
    session([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]);

    setAdminPanelContext($tenant);

    Livewire::withQueryParams([
        'nav' => [
            'source_surface' => 'finding.list_row',
            'canonical_route_name' => 'admin.operations.index',
            'managed_environment_id' => (int) $tenant->getKey(),
            'back_label' => 'Back to findings',
            'back_url' => '/admin/findings?tenant='.$tenant->external_id,
        ],
    ])
        ->actingAs($user)
        ->test(Operations::class)
        ->assertActionVisible('operate_hub_back_to_origin_operations');
});

it('does not register legacy operation resource routes', function (): void {
    expect(Route::has('filament.admin.resources.operations.index'))->toBeFalse();
    expect(Route::has('filament.admin.resources.operations.view'))->toBeFalse();
});

it('has reserved Monitoring placeholder pages for Alerts and Audit Log', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant($tenant, role: 'owner');

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->followingRedirects()
        ->get('/admin/alerts')
        ->assertOk();

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get('/admin/audit-log')
        ->assertOk();
});
