<?php

declare(strict_types=1);

use App\Filament\Resources\EvidenceSnapshotResource;
use App\Filament\Resources\ManagedEnvironmentResource;
use App\Models\EvidenceSnapshot;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Support\Auth\Capabilities;
use App\Support\Evidence\EvidenceCompletenessState;
use App\Support\Evidence\EvidenceSnapshotStatus;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Support\Facades\Gate;

it('routes legacy managed-environment edit helpers to the inspectable environment dashboard', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user] = createUserWithTenant($tenant, role: 'readonly');

    $this->actingAs($user)
        ->get(ManagedEnvironmentResource::getUrl('edit', ['record' => $tenant]))
        ->assertSuccessful()
        ->assertSee('Environment governance overview');
});

it('returns 404 for a non-member attempting to access a workspace managed-tenant list', function (): void {
    $workspace = Workspace::factory()->create();
    ManagedEnvironment::factory()->create(['workspace_id' => $workspace->getKey()]);

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

    $otherWorkspace = Workspace::factory()->create();

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

    $user->forceFill(['last_workspace_id' => $otherWorkspace->getKey()])->save();

    $this->actingAs($user)
        ->get('/admin/w/'.$workspace->slug.'/managed-tenants')
        ->assertNotFound();
});

it('returns 403 for an in-scope tenant member without evidence view capability on the evidence list', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user] = createUserWithTenant($tenant, role: 'owner');

    Gate::define(Capabilities::EVIDENCE_VIEW, fn (): bool => false);

    $this->actingAs($user)
        ->get(EvidenceSnapshotResource::getUrl('index', tenant: $tenant))
        ->assertForbidden();
});

it('returns 404 for a non-member attempting to access an evidence snapshot detail route', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    $snapshot = EvidenceSnapshot::query()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'status' => EvidenceSnapshotStatus::Active->value,
        'completeness_state' => EvidenceCompletenessState::Complete->value,
        'summary' => [],
        'generated_at' => now(),
    ]);

    [$user] = createUserWithTenant(role: 'owner');

    $this->actingAs($user)
        ->get(EvidenceSnapshotResource::getUrl('view', ['record' => $snapshot], tenant: $tenant))
        ->assertNotFound();
});

it('suppresses non-entitled tenants from the workspace evidence overview', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    [$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');
    $tenantDenied = ManagedEnvironment::factory()->create(['workspace_id' => (int) $tenantA->workspace_id]);
    createUserWithTenant(tenant: $tenantDenied, user: $user, role: 'owner');

    Gate::define(Capabilities::EVIDENCE_VIEW, fn (User $actor, ManagedEnvironment $tenant): bool => (int) $tenant->getKey() === (int) $tenantA->getKey());

    $allowedSnapshot = EvidenceSnapshot::query()->create([
        'managed_environment_id' => (int) $tenantA->getKey(),
        'workspace_id' => (int) $tenantA->workspace_id,
        'status' => EvidenceSnapshotStatus::Active->value,
        'completeness_state' => EvidenceCompletenessState::Complete->value,
        'summary' => ['missing_dimensions' => 0, 'stale_dimensions' => 0],
        'generated_at' => now(),
    ]);

    $deniedSnapshot = EvidenceSnapshot::query()->create([
        'managed_environment_id' => (int) $tenantDenied->getKey(),
        'workspace_id' => (int) $tenantDenied->workspace_id,
        'status' => EvidenceSnapshotStatus::Active->value,
        'completeness_state' => EvidenceCompletenessState::Missing->value,
        'summary' => ['missing_dimensions' => 2, 'stale_dimensions' => 0],
        'generated_at' => now(),
    ]);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id])
        ->get(route('admin.evidence.overview'))
        ->assertOk()
        ->assertSee(EvidenceSnapshotResource::getUrl('view', ['record' => $allowedSnapshot], tenant: $tenantA, panel: 'admin'))
        ->assertDontSee(EvidenceSnapshotResource::getUrl('view', ['record' => $deniedSnapshot], tenant: $tenantDenied, panel: 'admin'));
});
