<?php

declare(strict_types=1);

use App\Models\OperationRun;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Services\Graph\GraphClientInterface;
use App\Support\OperationRunLinks;
use App\Support\Verification\VerificationReportWriter;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;

it('allows access to Monitoring → Operations for workspace members', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant($tenant, role: 'owner');

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => 'policy.sync',
        'status' => 'queued',
        'outcome' => 'pending',
        'initiator_name' => 'System',
        'run_identity_hash' => 'hash123',
    ]);

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(route('admin.operations.index', ['workspace' => $tenant->workspace]))
        ->assertSuccessful()
        ->assertSee('Policy sync');
});

it('renders Monitoring → Operations pages DB-only (never calls Graph)', 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',
        'status' => 'queued',
        'outcome' => 'pending',
        'initiator_name' => 'System',
        'run_identity_hash' => 'hash123',
    ]);

    $this->mock(GraphClientInterface::class, function ($mock): void {
        $mock->shouldReceive('listPolicies')->never();
        $mock->shouldReceive('getPolicy')->never();
        $mock->shouldReceive('getOrganization')->never();
        $mock->shouldReceive('applyPolicy')->never();
        $mock->shouldReceive('getServicePrincipalPermissions')->never();
        $mock->shouldReceive('request')->never();
    });

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(route('admin.operations.index', ['workspace' => $tenant->workspace]))
        ->assertSuccessful();

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(route('admin.operations.view', ['workspace' => $tenant->workspace, 'run' => (int) $run->getKey()]))
        ->assertSuccessful();
});

it('keeps the operations list workspace-scoped when tenant context is set', 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'],
    ]);

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

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

    Filament::setTenant($tenantA, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id])
        ->get(route('admin.operations.index', ['workspace' => $tenantA->workspace]))
        ->assertSee('Policy sync')
        ->assertSee('Inventory sync');
});

it('allows readonly users to view operations list and detail', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant($tenant, role: 'readonly');

    $run = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => 'policy.sync',
        'status' => 'queued',
        'outcome' => 'pending',
        'initiator_name' => 'System',
        'run_identity_hash' => 'hash123',
    ]);

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(route('admin.operations.index', ['workspace' => $tenant->workspace]))
        ->assertSuccessful()
        ->assertSee('Policy sync');

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(route('admin.operations.view', ['workspace' => $tenant->workspace, 'run' => (int) $run->getKey()]))
        ->assertSuccessful()
        ->assertSee(\App\Support\OperationRunLinks::identifier($run));
});

it('returns 404 when viewing an operation run outside workspace membership', function (): void {
    $run = OperationRun::factory()->create();

    $user = User::factory()->create();

    $this->actingAs($user)
        ->get(route('admin.operations.view', ['workspace' => $run->workspace, 'run' => (int) $run->getKey()]))
        ->assertNotFound();
});

it('renders shared verification family markers on monitoring operation detail for workspace members', 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' => 'provider.connection.check',
        'status' => 'completed',
        'outcome' => 'blocked',
        'initiator_name' => 'System',
        'run_identity_hash' => 'hash123',
        'context' => [
            'verification_report' => VerificationReportWriter::build('provider.connection.check', [
                [
                    'key' => 'provider_connection',
                    'title' => 'Provider connection preflight',
                    'status' => 'fail',
                    'severity' => 'critical',
                    'blocking' => true,
                    'reason_code' => 'provider_connection_missing',
                    'message' => 'No provider connection configured.',
                    'evidence' => [],
                    'next_steps' => [],
                ],
            ]),
        ],
    ]);

    Filament::setTenant(null, true);

    $response = $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(route('admin.operations.view', ['workspace' => $tenant->workspace, 'run' => (int) $run->getKey()]));

    $response->assertSuccessful()->assertSee('Provider connection preflight');

    expect($response->getContent())
        ->toContain('data-shared-detail-family="verification-report"')
        ->toContain('data-host-kind="operation_run_detail"');
});
