<?php

declare(strict_types=1);

use App\Filament\Pages\Findings\MyFindingsInbox;
use App\Filament\Resources\FindingResource;
use App\Models\Finding;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Services\Auth\CapabilityResolver;
use App\Support\Auth\Capabilities;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Support\Facades\Gate;
use Livewire\Livewire;

use function Pest\Laravel\mock;

it('redirects inbox visits without workspace context into the existing workspace chooser flow', function (): void {
    $user = User::factory()->create();

    $workspaceA = Workspace::factory()->create();
    $workspaceB = Workspace::factory()->create();

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

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

    $this->actingAs($user)
        ->get(MyFindingsInbox::getUrl(panel: 'admin'))
        ->assertRedirect('/admin/choose-workspace');
});

it('returns 404 for users outside the active workspace on the inbox route', function (): void {
    $user = User::factory()->create();
    $workspace = Workspace::factory()->create();

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

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
        ->get(MyFindingsInbox::getUrl(panel: 'admin'))
        ->assertNotFound();
});

it('keeps the inbox accessible while suppressing blocked-tenant rows and summary counts', function (): void {
    $tenant = ManagedEnvironment::factory()->create(['status' => 'active']);
    [$user, $tenant] = createUserWithTenant($tenant, role: 'readonly', workspaceRole: 'readonly');

    $finding = Finding::factory()->for($tenant)->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'assignee_user_id' => (int) $user->getKey(),
        'owner_user_id' => (int) $user->getKey(),
        'status' => Finding::STATUS_NEW,
    ]);

    mock(CapabilityResolver::class, function ($mock) use ($tenant): void {
        $mock->shouldReceive('primeMemberships')->once();
        $mock->shouldReceive('isMember')->andReturnTrue();
        $mock->shouldReceive('can')
            ->andReturnUsing(static function (User $user, ManagedEnvironment $resolvedTenant, string $capability) use ($tenant): bool {
                expect((int) $resolvedTenant->getKey())->toBe((int) $tenant->getKey());

                return $capability === Capabilities::TENANT_FINDINGS_VIEW ? false : false;
            });
    });

    $this->actingAs($user);
    setAdminPanelContext();
    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);

    $component = Livewire::actingAs($user)->test(MyFindingsInbox::class)
        ->assertCanNotSeeTableRecords([$finding])
        ->assertSee('No visible assigned findings right now');

    expect($component->instance()->summaryCounts())->toBe([
        'open_assigned' => 0,
        'overdue_assigned' => 0,
    ]);
});

it('suppresses hidden-tenant findings and keeps their detail route not found', function (): void {
    $visibleTenant = ManagedEnvironment::factory()->create(['status' => 'active']);
    [$user, $visibleTenant] = createUserWithTenant($visibleTenant, role: 'readonly', workspaceRole: 'readonly');

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

    $visibleFinding = Finding::factory()->for($visibleTenant)->create([
        'workspace_id' => (int) $visibleTenant->workspace_id,
        'assignee_user_id' => (int) $user->getKey(),
        'owner_user_id' => (int) $user->getKey(),
        'status' => Finding::STATUS_TRIAGED,
    ]);

    $hiddenFinding = Finding::factory()->for($hiddenTenant)->create([
        'workspace_id' => (int) $hiddenTenant->workspace_id,
        'assignee_user_id' => (int) $user->getKey(),
        'owner_user_id' => (int) $user->getKey(),
        'status' => Finding::STATUS_NEW,
    ]);

    $this->actingAs($user);
    setAdminPanelContext();
    session()->put(WorkspaceContext::SESSION_KEY, (int) $visibleTenant->workspace_id);

    Livewire::actingAs($user)
        ->test(MyFindingsInbox::class)
        ->assertCanSeeTableRecords([$visibleFinding])
        ->assertCanNotSeeTableRecords([$hiddenFinding]);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $visibleTenant->workspace_id])
        ->get(FindingResource::getUrl('view', ['record' => $hiddenFinding], panel: 'admin', tenant: $hiddenTenant))
        ->assertNotFound();
});

it('preserves forbidden detail destinations for workspace members who still lack findings capability', function (): void {
    $tenant = ManagedEnvironment::factory()->create(['status' => 'active']);
    [$user, $tenant] = createUserWithTenant($tenant, role: 'readonly', workspaceRole: 'readonly');

    $finding = Finding::factory()->for($tenant)->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'assignee_user_id' => (int) $user->getKey(),
        'owner_user_id' => (int) $user->getKey(),
        'status' => Finding::STATUS_NEW,
    ]);

    mock(CapabilityResolver::class, function ($mock) use ($tenant): void {
        $mock->shouldReceive('primeMemberships')->once();
        $mock->shouldReceive('isMember')->andReturnTrue();
        $mock->shouldReceive('can')
            ->andReturnUsing(static function (User $user, ManagedEnvironment $resolvedTenant, string $capability) use ($tenant): bool {
                expect((int) $resolvedTenant->getKey())->toBe((int) $tenant->getKey());

                return $capability === Capabilities::TENANT_FINDINGS_VIEW ? false : false;
            });
    });

    $this->actingAs($user);
    setAdminPanelContext();
    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);

    Livewire::actingAs($user)
        ->test(MyFindingsInbox::class)
        ->assertCanNotSeeTableRecords([$finding]);

    Gate::define(Capabilities::TENANT_FINDINGS_VIEW, static function (User $user, ?ManagedEnvironment $resolvedTenant = null): bool {
        return false;
    });

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(FindingResource::getUrl('view', ['record' => $finding], panel: 'admin', tenant: $tenant))
        ->assertForbidden();
});
