<?php

declare(strict_types=1);

use App\Filament\Pages\Findings\FindingsIntakeQueue;
use App\Filament\Pages\Findings\MyFindingsInbox;
use App\Models\AuditLog;
use App\Models\Finding;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Services\Findings\FindingWorkflowService;
use App\Support\Audit\AuditActionId;
use App\Support\Workspaces\WorkspaceContext;
use Livewire\Livewire;

it('mounts the claim confirmation and moves the finding into my findings without changing owner or lifecycle', function (): void {
    $tenant = ManagedEnvironment::factory()->create(['status' => 'active']);
    [$user, $tenant] = createUserWithTenant($tenant, role: 'manager', workspaceRole: 'manager');

    $owner = User::factory()->create();
    createUserWithTenant($tenant, $owner, role: 'owner', workspaceRole: 'manager');

    $finding = Finding::factory()->reopened()->for($tenant)->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'owner_user_id' => (int) $owner->getKey(),
        'assignee_user_id' => null,
        'subject_external_id' => 'claimable',
    ]);

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

    Livewire::actingAs($user)
        ->test(FindingsIntakeQueue::class)
        ->assertTableActionVisible('claim', $finding)
        ->mountTableAction('claim', $finding)
        ->callMountedTableAction()
        ->assertCanNotSeeTableRecords([$finding]);

    $finding->refresh();

    expect((int) $finding->assignee_user_id)->toBe((int) $user->getKey())
        ->and((int) $finding->owner_user_id)->toBe((int) $owner->getKey())
        ->and($finding->status)->toBe(Finding::STATUS_REOPENED);

    $audit = AuditLog::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('resource_type', 'finding')
        ->where('resource_id', (string) $finding->getKey())
        ->where('action', AuditActionId::FindingAssigned->value)
        ->latest('id')
        ->first();

    expect($audit)->not->toBeNull()
        ->and(data_get($audit?->metadata ?? [], 'assignee_user_id'))->toBe((int) $user->getKey())
        ->and(data_get($audit?->metadata ?? [], 'owner_user_id'))->toBe((int) $owner->getKey());

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

it('refuses a stale claim after another operator already claimed the finding first', function (): void {
    $tenant = ManagedEnvironment::factory()->create(['status' => 'active']);
    [$operatorA, $tenant] = createUserWithTenant($tenant, role: 'manager', workspaceRole: 'manager');

    $operatorB = User::factory()->create();
    createUserWithTenant($tenant, $operatorB, role: 'manager', workspaceRole: 'manager');

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

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

    $component = Livewire::actingAs($operatorA)
        ->test(FindingsIntakeQueue::class)
        ->mountTableAction('claim', $finding);

    app(FindingWorkflowService::class)->claim($finding, $tenant, $operatorB);

    $component
        ->callMountedTableAction();

    expect((int) $finding->refresh()->assignee_user_id)->toBe((int) $operatorB->getKey());

    Livewire::actingAs($operatorA)
        ->test(FindingsIntakeQueue::class)
        ->assertCanNotSeeTableRecords([$finding]);

    expect(
        AuditLog::query()
            ->where('managed_environment_id', (int) $tenant->getKey())
            ->where('resource_type', 'finding')
            ->where('resource_id', (string) $finding->getKey())
            ->where('action', AuditActionId::FindingAssigned->value)
            ->count()
    )->toBe(1);
});
