<?php

declare(strict_types=1);

use App\Filament\Pages\Operations\TenantlessOperationRunViewer;
use App\Filament\Pages\EnvironmentDashboard;
use App\Models\OperationRun;
use App\Models\SupportRequest;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Models\WorkspaceMembership;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;
use App\Support\SupportRequests\SupportRequestSubmissionService;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Livewire\Livewire;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

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

function spec256AuthorizationTenantComponent(User $user, ManagedEnvironment $tenant): \Livewire\Features\SupportTesting\Testable
{
    test()->actingAs($user);
    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
    setAdminEnvironmentContext($tenant);

    return Livewire::actingAs($user)->test(EnvironmentDashboard::class);
}

function spec256AuthorizationOperationComponent(User $user, OperationRun $run): \Livewire\Features\SupportTesting\Testable
{
    test()->actingAs($user);
    Filament::setTenant(null, true);
    session()->put(WorkspaceContext::SESSION_KEY, (int) $run->workspace_id);

    return Livewire::actingAs($user)->test(TenantlessOperationRunViewer::class, ['run' => $run]);
}

function spec256AuthorizationRun(ManagedEnvironment $tenant): OperationRun
{
    return OperationRun::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Failed->value,
        'completed_at' => now(),
    ]);
}

it('keeps external handoff actions forbidden for entitled tenant members without support-create capability', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'readonly');

    spec256AuthorizationTenantComponent($user, $tenant)
        ->assertActionVisible('requestSupport')
        ->assertActionDisabled('requestSupport')
        ->call('authorizeTenantSupportRequest')
        ->assertForbidden();

    expect(SupportRequest::query()->count())->toBe(0);
});

it('keeps external handoff actions forbidden for entitled run viewers without support-create capability', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'readonly');
    $run = spec256AuthorizationRun($tenant);

    spec256AuthorizationOperationComponent($user, $run)
        ->assertActionVisible('requestSupport')
        ->assertActionDisabled('requestSupport')
        ->call('authorizeOperationRunSupportRequest')
        ->assertForbidden();

    expect(SupportRequest::query()->count())->toBe(0);
});

it('does not reveal latest tenant handoff summaries to workspace members without tenant entitlement', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    $user = User::factory()->create();

    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'user_id' => (int) $user->getKey(),
        'role' => 'operator',
    ]);
    createUserWithTenant(
        tenant: ManagedEnvironment::factory()->create(['workspace_id' => (int) $tenant->workspace_id]),
        user: $user,
        role: 'operator',
    );

    SupportRequest::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'primary_context_type' => SupportRequest::PRIMARY_CONTEXT_TENANT,
        'external_handoff_mode' => SupportRequest::EXTERNAL_HANDOFF_MODE_LINK_EXISTING_TICKET,
        'external_ticket_reference' => 'PSA-HIDDEN',
    ]);

    try {
        app(SupportRequestSubmissionService::class)->latestTenantHandoffSummary($tenant, $user);
        $this->fail('Expected latest handoff summary to deny as not found.');
    } catch (HttpExceptionInterface $exception) {
        expect($exception->getStatusCode())->toBe(404);
    }
});

it('does not reveal latest run handoff summaries outside the run tenant entitlement', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    $user = User::factory()->create();

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

    $run = spec256AuthorizationRun($tenant);

    SupportRequest::factory()
        ->forOperationRun($run)
        ->create([
            'external_handoff_mode' => SupportRequest::EXTERNAL_HANDOFF_MODE_LINK_EXISTING_TICKET,
            'external_ticket_reference' => 'PSA-RUN-HIDDEN',
        ]);

    try {
        app(SupportRequestSubmissionService::class)->latestOperationRunHandoffSummary($run, $user);
        $this->fail('Expected latest run handoff summary to deny as not found.');
    } catch (HttpExceptionInterface $exception) {
        expect($exception->getStatusCode())->toBe(404);
    }
});
