<?php

declare(strict_types=1);

use App\Filament\Resources\ManagedEnvironmentResource;
use App\Filament\Resources\ManagedEnvironmentResource\Pages\ListManagedEnvironments;
use App\Filament\Resources\ManagedEnvironmentResource\Pages\ViewManagedEnvironment;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Livewire\Livewire;

describe('ManagedEnvironment resource authorization', function () {
    it('cannot be created by non-members', function () {
        $user = User::factory()->create();

        $this->actingAs($user);

        expect(ManagedEnvironmentResource::canCreate())->toBeFalse();
    });

    it('cannot be created via CRUD (onboarding wizard is the only path)', function () {
        [$user] = createUserWithTenant(role: 'manager');

        $this->actingAs($user);

        expect(ManagedEnvironmentResource::canCreate())->toBeFalse();
    });

    it('can be edited by managers (TENANT_MANAGE)', function () {
        [$user, $tenant] = createUserWithTenant(role: 'manager');

        $this->actingAs($user);

        expect(ManagedEnvironmentResource::canEdit($tenant))->toBeTrue();
    });

    it('cannot be deleted by managers (TENANT_DELETE)', function () {
        [$user, $tenant] = createUserWithTenant(role: 'manager');

        $this->actingAs($user);

        expect(ManagedEnvironmentResource::canDelete($tenant))->toBeFalse();
    });

    it('can be deleted by owners (TENANT_DELETE)', function () {
        [$user, $tenant] = createUserWithTenant(role: 'owner');

        $this->actingAs($user);

        expect(ManagedEnvironmentResource::canDelete($tenant))->toBeTrue();
    });

    it('cannot edit tenants it cannot access', function () {
        [$user] = createUserWithTenant(role: 'manager');
        $otherTenant = ManagedEnvironment::factory()->create();

        $this->actingAs($user);

        expect(ManagedEnvironmentResource::canEdit($otherTenant))->toBeFalse();
    });

    it('returns not found for tenant detail pages outside the actor tenant scope', function (): void {
        [$user] = createUserWithTenant(role: 'owner', ensureDefaultMicrosoftProviderConnection: false);
        $otherTenant = ManagedEnvironment::factory()->active()->create();

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

    it('returns not found for numeric tenant detail paths outside the actor tenant scope', function (): void {
        [$user, $tenant] = createUserWithTenant(role: 'owner', ensureDefaultMicrosoftProviderConnection: false);
        $otherTenant = ManagedEnvironment::factory()->active()->create();

        $this->actingAs($user)
            ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
            ->get(ManagedEnvironmentResource::getUrl('view', ['record' => (string) $otherTenant->getKey()], panel: 'admin'))
            ->assertNotFound();
    });

    it('does not grant lifecycle mutation abilities for inaccessible tenants regardless of lifecycle state', function (\Closure $tenantFactory): void {
        [$user] = createUserWithTenant(role: 'owner', ensureDefaultMicrosoftProviderConnection: false);
        $otherTenant = $tenantFactory();

        $this->actingAs($user);

        expect(ManagedEnvironmentResource::canEdit($otherTenant))->toBeFalse()
            ->and(ManagedEnvironmentResource::canDelete($otherTenant))->toBeFalse();
    })->with([
        'draft' => [fn (): ManagedEnvironment => ManagedEnvironment::factory()->draft()->create()],
        'onboarding' => [fn (): ManagedEnvironment => ManagedEnvironment::factory()->onboarding()->create()],
        'active' => [fn (): ManagedEnvironment => ManagedEnvironment::factory()->active()->create()],
        'archived' => [fn (): ManagedEnvironment => ManagedEnvironment::factory()->archived()->create()],
    ]);

    it('keeps onboarding and archived tenants manageable when the actor is entitled', function () {
        $onboardingTenant = ManagedEnvironment::factory()->onboarding()->create();
        [$user, $onboardingTenant] = createUserWithTenant(
            tenant: $onboardingTenant,
            role: 'manager',
            ensureDefaultMicrosoftProviderConnection: false,
        );

        $archivedTenant = ManagedEnvironment::factory()->archived()->create([
            'workspace_id' => (int) $onboardingTenant->workspace_id,
        ]);

        createUserWithTenant(
            tenant: $archivedTenant,
            user: $user,
            role: 'manager',
            workspaceRole: 'manager',
            ensureDefaultMicrosoftProviderConnection: false,
        );

        $archivedTenant = ManagedEnvironment::withTrashed()->findOrFail((int) $archivedTenant->getKey());

        $this->actingAs($user);

        expect(ManagedEnvironmentResource::canEdit($onboardingTenant))->toBeTrue()
            ->and(ManagedEnvironmentResource::canEdit($archivedTenant))->toBeTrue()
            ->and(ManagedEnvironmentResource::canDelete($onboardingTenant))->toBeFalse()
            ->and(ManagedEnvironmentResource::canDelete($archivedTenant))->toBeFalse();
    });

    it('keeps mutation capability checks separate from lifecycle-specific action visibility', function (): void {
        $onboardingTenant = ManagedEnvironment::factory()->onboarding()->create();
        [$user, $onboardingTenant] = createUserWithTenant(
            tenant: $onboardingTenant,
            role: 'owner',
            ensureDefaultMicrosoftProviderConnection: false,
        );

        $archivedTenant = ManagedEnvironment::factory()->archived()->create([
            'workspace_id' => (int) $onboardingTenant->workspace_id,
        ]);

        createUserWithTenant(
            tenant: $archivedTenant,
            user: $user,
            role: 'owner',
            workspaceRole: 'owner',
            ensureDefaultMicrosoftProviderConnection: false,
        );

        $archivedTenant = ManagedEnvironment::withTrashed()->findOrFail((int) $archivedTenant->getKey());

        $this->actingAs($user);

        expect(ManagedEnvironmentResource::canDelete($onboardingTenant))->toBeTrue()
            ->and(ManagedEnvironmentResource::canDelete($archivedTenant))->toBeTrue();
    });

    it('keeps the tenant resource index usable with no selected tenant context', function () {
        [$user, $tenant] = createUserWithTenant(role: 'owner');

        $this->actingAs($user)
            ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
            ->get(ManagedEnvironmentResource::getUrl(panel: 'admin'))
            ->assertSuccessful()
            ->assertSee((string) $tenant->name);
    });

    it('resolves archive and verify actions as enabled for owners on active tenant surfaces', function (): void {
        $tenant = ManagedEnvironment::factory()->active()->create();
        [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner', ensureDefaultMicrosoftProviderConnection: false);

        session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);

        Livewire::actingAs($user)
            ->test(ListManagedEnvironments::class)
            ->assertTableActionVisible('archive', $tenant)
            ->assertTableActionEnabled('archive', $tenant)
            ->assertTableActionVisible('syncTenant', $tenant)
            ->assertTableActionEnabled('syncTenant', $tenant)
            ->assertTableActionVisible('verify', $tenant)
            ->assertTableActionEnabled('verify', $tenant);

        Filament::setTenant(null, true);

        Livewire::actingAs($user)
            ->test(ViewManagedEnvironment::class, ['record' => $tenant->getRouteKey()])
            ->assertActionVisible('archive')
            ->assertActionEnabled('archive')
            ->assertActionVisible('syncTenant')
            ->assertActionEnabled('syncTenant')
            ->assertActionVisible('verify')
            ->assertActionEnabled('verify');
    });

    it('keeps lifecycle mutation actions visible but disabled for managers without delete capability', function (): void {
        $tenant = ManagedEnvironment::factory()->active()->create();
        [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'manager', ensureDefaultMicrosoftProviderConnection: false);

        session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);

        Livewire::actingAs($user)
            ->test(ListManagedEnvironments::class)
            ->assertTableActionVisible('archive', $tenant)
            ->assertTableActionDisabled('archive', $tenant);

        Filament::setTenant(null, true);

        Livewire::actingAs($user)
            ->test(ViewManagedEnvironment::class, ['record' => $tenant->getRouteKey()])
            ->assertActionVisible('archive')
            ->assertActionDisabled('archive');
    });
});
