<?php

declare(strict_types=1);

use App\Models\OperationRun;
use App\Models\Tenant;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;

uses(\Illuminate\Foundation\Testing\RefreshDatabase::class);

test('operation runs default to the active tenant when tenant context is set', function (): void {
    $tenantA = Tenant::factory()->create();
    [$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner');

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

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

    OperationRun::factory()->create([
        'tenant_id' => (int) $tenantA->getKey(),
        'workspace_id' => (int) $tenantA->workspace_id,
        'type' => 'policy.sync',
        'status' => 'queued',
        'outcome' => 'pending',
        'initiator_name' => 'Tenant A Scope',
    ]);

    OperationRun::factory()->create([
        'tenant_id' => (int) $tenantB->getKey(),
        'workspace_id' => (int) $tenantB->workspace_id,
        'type' => 'inventory_sync',
        'status' => 'queued',
        'outcome' => 'pending',
        'initiator_name' => 'Tenant B Scope',
    ]);

    Filament::setTenant($tenantA, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id])
        ->get('/admin/operations')
        ->assertOk()
        ->assertSee('Tenant A Scope')
        ->assertDontSee('Tenant B Scope');
});

test('operation run view is not accessible cross-workspace', function (): void {
    $workspaceA = Workspace::factory()->create();
    $workspaceB = Workspace::factory()->create();

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

    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $workspaceA->getKey(),
        'user_id' => (int) $user->getKey(),
        'role' => 'owner',
    ]);

    $tenantB = Tenant::factory()->create([
        'status' => 'active',
        'workspace_id' => (int) $workspaceB->getKey(),
    ]);

    $runB = OperationRun::factory()->create([
        'tenant_id' => (int) $tenantB->getKey(),
        'workspace_id' => (int) $workspaceB->getKey(),
        'type' => 'inventory_sync',
        'status' => 'queued',
        'outcome' => 'pending',
    ]);

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

test('readonly users can view operation runs in their workspace', function (): void {
    $tenant = Tenant::factory()->create();

    $run = OperationRun::factory()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => 'baseline_compare',
        'status' => 'queued',
        'outcome' => 'pending',
    ]);

    [$user, $tenant] = createUserWithTenant($tenant, role: 'readonly');

    Filament::setTenant(null, true);

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

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

test('tenant-associated run viewer requires tenant entitlement even for workspace members', function (): void {
    $workspace = Workspace::factory()->create();
    $tenant = Tenant::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'status' => 'active',
    ]);

    $run = OperationRun::factory()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $workspace->getKey(),
        'type' => 'provider.connection.check',
        'status' => 'queued',
        'outcome' => 'pending',
    ]);

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

    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'user_id' => (int) $user->getKey(),
        'role' => 'owner',
    ]);

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

test('baseline compare runs with RBAC context still require tenant entitlement', function (): void {
    $workspace = Workspace::factory()->create();
    $tenant = Tenant::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'status' => 'active',
    ]);

    $run = OperationRun::factory()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $workspace->getKey(),
        'type' => 'baseline_compare',
        'status' => 'completed',
        'outcome' => 'succeeded',
        'context' => [
            'baseline_profile_id' => 42,
            'baseline_compare' => [
                'rbac_role_definitions' => [
                    'total_compared' => 3,
                    'unchanged' => 1,
                    'modified' => 1,
                    'missing' => 1,
                    'unexpected' => 0,
                ],
            ],
        ],
    ]);

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

    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'user_id' => (int) $user->getKey(),
        'role' => 'owner',
    ]);

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