<?php

declare(strict_types=1);

use App\Filament\Resources\FindingResource\Pages\ListFindings;
use App\Models\Finding;
use App\Models\FindingException;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Filament\Forms\Components\Field;
use Filament\Forms\Components\Select;
use Filament\Schemas\Components\Text;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

uses(RefreshDatabase::class);

it('supports triage start resolve and reopen via row actions', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'manager');
    $this->actingAs($user);
    Filament::setTenant($tenant, true);

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

    $component = Livewire::test(ListFindings::class);

    $component
        ->callTableAction('triage', $finding)
        ->assertHasNoTableActionErrors();

    $finding->refresh();
    expect($finding->status)->toBe(Finding::STATUS_TRIAGED)
        ->and($finding->triaged_at)->not->toBeNull();

    $component
        ->callTableAction('start_progress', $finding)
        ->assertHasNoTableActionErrors();

    $finding->refresh();
    expect($finding->status)->toBe(Finding::STATUS_IN_PROGRESS)
        ->and($finding->in_progress_at)->not->toBeNull();

    $component
        ->callTableAction('resolve', $finding, [
            'resolved_reason' => Finding::RESOLVE_REASON_REMEDIATED,
        ])
        ->assertHasNoTableActionErrors();

    $finding->refresh();
    expect($finding->status)->toBe(Finding::STATUS_RESOLVED)
        ->and($finding->resolved_reason)->toBe(Finding::RESOLVE_REASON_REMEDIATED)
        ->and($finding->resolved_at)->not->toBeNull();

    $component
        ->filterTable('open', false)
        ->callTableAction('reopen', $finding, [
            'reopen_reason' => Finding::REOPEN_REASON_MANUAL_REASSESSMENT,
        ])
        ->assertHasNoTableActionErrors();

    $finding->refresh();
    expect($finding->status)->toBe(Finding::STATUS_REOPENED)
        ->and($finding->reopened_at)->not->toBeNull()
        ->and($finding->due_at)->not->toBeNull();
});

it('supports close and request exception via row actions', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    $closeFinding = Finding::factory()->for($tenant)->create([
        'status' => Finding::STATUS_NEW,
    ]);

    $exceptionFinding = Finding::factory()->for($tenant)->create([
        'status' => Finding::STATUS_NEW,
    ]);

    $component = Livewire::test(ListFindings::class);

    $component
        ->callTableAction('close', $closeFinding, [
            'closed_reason' => Finding::CLOSE_REASON_DUPLICATE,
        ])
        ->assertHasNoTableActionErrors();

    $component
        ->callTableAction('request_exception', $exceptionFinding, [
            'owner_user_id' => (int) $user->getKey(),
            'request_reason' => 'accepted by security',
            'review_due_at' => now()->addDays(14)->toDateTimeString(),
            'expires_at' => now()->addDays(30)->toDateTimeString(),
        ])
        ->assertHasNoTableActionErrors();

    expect($closeFinding->refresh()->status)->toBe(Finding::STATUS_CLOSED)
        ->and($closeFinding->closed_reason)->toBe(Finding::CLOSE_REASON_DUPLICATE);

    $exception = FindingException::query()
        ->where('finding_id', (int) $exceptionFinding->getKey())
        ->first();

    expect($exception)->toBeInstanceOf(FindingException::class)
        ->and($exception?->status)->toBe(FindingException::STATUS_PENDING)
        ->and($exception?->request_reason)->toBe('accepted by security');
});

it('keeps unchanged roles intact and exposes explicit assignment help text on row actions', function (): void {
    [$manager, $tenant] = createUserWithTenant(role: 'manager');
    $this->actingAs($manager);
    Filament::setTenant($tenant, true);

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

    $initialAssignee = User::factory()->create();
    createUserWithTenant(tenant: $tenant, user: $initialAssignee, role: 'operator');

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

    $replacementAssignee = User::factory()->create();
    createUserWithTenant(tenant: $tenant, user: $replacementAssignee, role: 'operator');

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

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

    $component = Livewire::test(ListFindings::class)
        ->mountTableAction('assign', $finding)
        ->assertFormFieldExists('owner_user_id', function (Select $field): bool {
            $helperText = collect($field->getChildSchema(Field::BELOW_CONTENT_SCHEMA_KEY)?->getComponents() ?? [])
                ->filter(fn (mixed $component): bool => $component instanceof Text)
                ->map(fn (Text $component): string => (string) $component->getContent())
                ->implode(' ');

            return $field->getLabel() === 'Accountable owner'
                && str_contains($helperText, 'accountable for ensuring the finding reaches a governed outcome');
        })
        ->assertFormFieldExists('assignee_user_id', function (Select $field): bool {
            $helperText = collect($field->getChildSchema(Field::BELOW_CONTENT_SCHEMA_KEY)?->getComponents() ?? [])
                ->filter(fn (mixed $component): bool => $component instanceof Text)
                ->map(fn (Text $component): string => (string) $component->getContent())
                ->implode(' ');

            return $field->getLabel() === 'Active assignee'
                && str_contains($helperText, 'currently expected to perform or coordinate the remediation work');
        });

    $component
        ->callTableAction('assign', $finding, [
            'assignee_user_id' => (int) $replacementAssignee->getKey(),
            'owner_user_id' => (int) $initialOwner->getKey(),
        ])
        ->assertHasNoTableActionErrors();

    $finding->refresh();
    expect((int) $finding->assignee_user_id)->toBe((int) $replacementAssignee->getKey())
        ->and((int) $finding->owner_user_id)->toBe((int) $initialOwner->getKey());

    $component
        ->callTableAction('assign', $finding, [
            'assignee_user_id' => (int) $replacementAssignee->getKey(),
            'owner_user_id' => (int) $replacementOwner->getKey(),
        ])
        ->assertHasNoTableActionErrors();

    $finding->refresh();
    expect((int) $finding->assignee_user_id)->toBe((int) $replacementAssignee->getKey())
        ->and((int) $finding->owner_user_id)->toBe((int) $replacementOwner->getKey());

    $component
        ->callTableAction('assign', $finding, [
            'assignee_user_id' => (int) $outsider->getKey(),
            'owner_user_id' => (int) $replacementOwner->getKey(),
        ]);

    $finding->refresh();
    expect((int) $finding->assignee_user_id)->toBe((int) $replacementAssignee->getKey())
        ->and((int) $finding->owner_user_id)->toBe((int) $replacementOwner->getKey());
});

it('returns 404 when a forged foreign-tenant assign row action is mounted', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    [$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');

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

    createUserWithTenant(tenant: $tenantB, user: $user, role: 'owner');

    $foreignFinding = Finding::factory()->for($tenantB)->create([
        'status' => Finding::STATUS_NEW,
    ]);

    $this->actingAs($user);
    Filament::setCurrentPanel('admin');
    Filament::setTenant(null, true);
    Filament::bootCurrentPanel();

    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenantA->workspace_id);
    session()->put(WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY, [
        (string) $tenantA->workspace_id => (int) $tenantA->getKey(),
    ]);

    $component = Livewire::actingAs($user)->test(ListFindings::class);

    expect(fn () => $component->instance()->mountTableAction('assign', (string) $foreignFinding->getKey()))
        ->toThrow(NotFoundHttpException::class);
});

it('keeps the admin workflow surface scoped to the canonical tenant', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    [$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');

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

    createUserWithTenant(tenant: $tenantB, user: $user, role: 'owner');

    $visibleFinding = Finding::factory()->for($tenantA)->create([
        'status' => Finding::STATUS_NEW,
    ]);

    $hiddenFinding = Finding::factory()->for($tenantB)->create([
        'status' => Finding::STATUS_NEW,
    ]);

    $this->actingAs($user);
    Filament::setCurrentPanel('admin');
    Filament::setTenant(null, true);
    Filament::bootCurrentPanel();

    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenantA->workspace_id);
    session()->put(WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY, [
        (string) $tenantA->workspace_id => (int) $tenantA->getKey(),
    ]);

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