<?php

declare(strict_types=1);

use App\Filament\Resources\PolicyResource\Pages\ViewPolicy;
use App\Filament\Resources\PolicyResource\RelationManagers\VersionsRelationManager;
use App\Models\Policy;
use App\Models\PolicyVersion;
use App\Models\RestoreRun;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

uses(RefreshDatabase::class);

describe('Policy versions relation manager restore-to-Intune UI enforcement', function () {
    it('disables restore action for readonly members', function (): void {
        [$user, $tenant] = createUserWithTenant(role: 'readonly');

        setAdminPanelContext($tenant);

        $policy = Policy::factory()->create([
            'managed_environment_id' => $tenant->id,
        ]);

        $version = PolicyVersion::factory()->create([
            'managed_environment_id' => $tenant->id,
            'policy_id' => $policy->id,
            'metadata' => [],
        ]);

        Livewire::actingAs($user)
            ->test(VersionsRelationManager::class, [
                'ownerRecord' => $policy,
                'pageClass' => ViewPolicy::class,
            ])
            ->assertTableActionDisabled('restore_to_intune', $version);
    });

    it('disables restore action for metadata-only snapshots', function (): void {
        [$user, $tenant] = createUserWithTenant(role: 'owner');

        setAdminPanelContext($tenant);

        $policy = Policy::factory()->create([
            'managed_environment_id' => $tenant->id,
        ]);

        $version = PolicyVersion::factory()->create([
            'managed_environment_id' => $tenant->id,
            'policy_id' => $policy->id,
            'metadata' => ['source' => 'metadata_only'],
        ]);

        Livewire::actingAs($user)
            ->test(VersionsRelationManager::class, [
                'ownerRecord' => $policy,
                'pageClass' => ViewPolicy::class,
            ])
            ->assertTableActionDisabled('restore_to_intune', $version);
    });

    it('hides restore action after membership is revoked mid-session', function (): void {
        [$user, $tenant] = createUserWithTenant(role: 'owner');

        setAdminPanelContext($tenant);

        $policy = Policy::factory()->create([
            'managed_environment_id' => $tenant->id,
        ]);

        $version = PolicyVersion::factory()->create([
            'managed_environment_id' => $tenant->id,
            'policy_id' => $policy->id,
            'metadata' => [],
        ]);

        $component = Livewire::actingAs($user)
            ->test(VersionsRelationManager::class, [
                'ownerRecord' => $policy,
                'pageClass' => ViewPolicy::class,
            ]);

        $user->tenants()->detach($tenant->getKey());
        \App\Models\WorkspaceMembership::query()
            ->where('workspace_id', (int) $tenant->workspace_id)
            ->where('user_id', (int) $user->getKey())
            ->delete();
        app(\App\Services\Auth\CapabilityResolver::class)->clearCache();
        app(\App\Services\Auth\WorkspaceCapabilityResolver::class)->clearCache();

        $component
            ->call('$refresh')
            ->assertTableActionHidden('restore_to_intune', $version);
    });

    it('returns 404 and starts no restore when a forged foreign-tenant version key is mounted', function (): void {
        [$user, $tenant] = createUserWithTenant(role: 'owner');

        setAdminPanelContext($tenant);

        $policy = Policy::factory()->create([
            'managed_environment_id' => $tenant->id,
        ]);

        $foreignTenant = \App\Models\ManagedEnvironment::factory()->create();
        $foreignPolicy = Policy::factory()->create([
            'managed_environment_id' => $foreignTenant->id,
        ]);
        $foreignVersion = PolicyVersion::factory()->create([
            'managed_environment_id' => $foreignTenant->id,
            'policy_id' => $foreignPolicy->id,
            'metadata' => [],
        ]);

        $component = Livewire::actingAs($user)
            ->test(VersionsRelationManager::class, [
                'ownerRecord' => $policy,
                'pageClass' => ViewPolicy::class,
            ]);

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

        expect(RestoreRun::query()->doesntExist())->toBeTrue();
    });
});
