<?php

declare(strict_types=1);

use App\Filament\System\Pages\Ops\Controls;
use App\Filament\Resources\RestoreRunResource;
use App\Filament\Resources\RestoreRunResource\Pages\CreateRestoreRun;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\OperationalControlActivation;
use App\Models\PlatformUser;
use App\Models\Policy;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Support\Auth\PlatformCapabilities;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

beforeEach(function (): void {
    putenv('INTUNE_TENANT_ID');
    unset($_ENV['INTUNE_TENANT_ID'], $_SERVER['INTUNE_TENANT_ID']);
});

function seedRestoreAuthorizationContext(): array
{
    $tenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => fake()->uuid(),
        'name' => 'Authorization ManagedEnvironment',
        'rbac_status' => 'ok',
        'rbac_last_checked_at' => now(),
    ]);

    $tenant->makeCurrent();
    ensureDefaultProviderConnection($tenant, 'microsoft');

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => fake()->uuid(),
        'policy_type' => 'deviceConfiguration',
        'display_name' => 'Authorization Restore Policy',
        'platform' => 'windows',
    ]);

    $backupSet = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Authorization Backup',
        'status' => 'completed',
        'item_count' => 1,
    ]);

    $backupItem = BackupItem::create([
        'managed_environment_id' => $tenant->id,
        'backup_set_id' => $backupSet->id,
        'policy_id' => $policy->id,
        'policy_identifier' => $policy->external_id,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'payload' => ['id' => $policy->external_id],
        'metadata' => ['displayName' => 'Authorization Restore Policy'],
    ]);

    Filament::setTenant($tenant, true);

    return [$tenant, $backupSet, $backupItem];
}

it('keeps non-members at 404 even when restore execution is paused', function (): void {
    [$tenant] = seedRestoreAuthorizationContext();

    OperationalControlActivation::factory()->workspaceScoped()->create([
        'control_key' => 'restore.execute',
        'workspace_id' => (int) $tenant->workspace_id,
        'reason_text' => 'Paused while access is under review.',
    ]);

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

    $this->actingAs($user)
        ->get(RestoreRunResource::getUrl('create', panel: 'admin', tenant: $tenant))
        ->assertNotFound();
});

it('keeps members without tenant-manage at 403 even when restore execution is paused', function (): void {
    [$tenant] = seedRestoreAuthorizationContext();

    OperationalControlActivation::factory()->workspaceScoped()->create([
        'control_key' => 'restore.execute',
        'workspace_id' => (int) $tenant->workspace_id,
        'reason_text' => 'Paused while access is under review.',
    ]);

    [$user] = createUserWithTenant(tenant: $tenant, role: 'operator');

    $this->actingAs($user)
        ->get(RestoreRunResource::getUrl('create', panel: 'admin', tenant: $tenant))
        ->assertForbidden();
});

it('shows paused-state feedback only to entitled users blocked by an operational control', function (): void {
    [$tenant, $backupSet, $backupItem] = seedRestoreAuthorizationContext();

    OperationalControlActivation::factory()->workspaceScoped()->create([
        'control_key' => 'restore.execute',
        'workspace_id' => (int) $tenant->workspace_id,
        'reason_text' => 'Paused for tenant-safe validation.',
    ]);

    [$user] = createUserWithTenant(tenant: $tenant, role: 'owner');

    $this->actingAs($user);

    Livewire::test(CreateRestoreRun::class)
        ->fillForm([
            'backup_set_id' => $backupSet->id,
        ])
        ->goToNextWizardStep()
        ->fillForm([
            'scope_mode' => 'selected',
            'backup_item_ids' => [$backupItem->id],
        ])
        ->goToNextWizardStep()
        ->callFormComponentAction('check_results', 'run_restore_checks')
        ->goToNextWizardStep()
        ->callFormComponentAction('preview_diffs', 'run_restore_preview')
        ->goToNextWizardStep()
        ->fillForm([
            'is_dry_run' => false,
            'acknowledged_impact' => true,
            'tenant_confirm' => 'Authorization ManagedEnvironment',
        ])
        ->call('create')
        ->assertNotified('Restore execution paused');
});

it('forbids ai execution controls for platform users missing system panel access', function (): void {
    $user = PlatformUser::factory()->create([
        'capabilities' => [
            PlatformCapabilities::OPS_CONTROLS_MANAGE,
        ],
        'is_active' => true,
    ]);

    $this->actingAs($user, 'platform')
        ->get(Controls::getUrl(panel: 'system'))
        ->assertForbidden();
});

it('forbids ai execution controls for platform users missing ops controls manage', function (): void {
    $user = PlatformUser::factory()->create([
        'capabilities' => [
            PlatformCapabilities::ACCESS_SYSTEM_PANEL,
        ],
        'is_active' => true,
    ]);

    $this->actingAs($user, 'platform')
        ->get(Controls::getUrl(panel: 'system'))
        ->assertForbidden();
});

it('shows ai execution controls only to platform users with the existing system control capabilities', function (): void {
    $user = PlatformUser::factory()->create([
        'capabilities' => [
            PlatformCapabilities::ACCESS_SYSTEM_PANEL,
            PlatformCapabilities::OPS_CONTROLS_MANAGE,
        ],
        'is_active' => true,
    ]);

    $this->actingAs($user, 'platform')
        ->get(Controls::getUrl(panel: 'system'))
        ->assertSuccessful()
        ->assertSee('AI execution');

    Livewire::actingAs($user, 'platform')
        ->test(Controls::class)
        ->assertActionVisible('pause_ai_execution')
        ->assertActionVisible('resume_ai_execution');
});