<?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');

        $tenant->makeCurrent();
        Filament::setTenant($tenant, true);

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

        $version = PolicyVersion::factory()->create([
            'tenant_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');

        $tenant->makeCurrent();
        Filament::setTenant($tenant, true);

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

        $version = PolicyVersion::factory()->create([
            'tenant_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');

        $tenant->makeCurrent();
        Filament::setTenant($tenant, true);

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

        $version = PolicyVersion::factory()->create([
            'tenant_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(\App\Services\Auth\CapabilityResolver::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');

        $tenant->makeCurrent();
        Filament::setTenant($tenant, true);

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

        $foreignTenant = \App\Models\Tenant::factory()->create();
        $foreignPolicy = Policy::factory()->create([
            'tenant_id' => $foreignTenant->id,
        ]);
        $foreignVersion = PolicyVersion::factory()->create([
            'tenant_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();
    });
});
