<?php

use App\Filament\Resources\RestoreRunResource\Pages\CreateRestoreRun;
use App\Jobs\ExecuteRestoreRunJob;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\ManagedEnvironment;
use App\Models\OperationRun;
use App\Models\Policy;
use App\Models\RestoreRun;
use App\Models\User;
use App\Support\RestoreRunStatus;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;
use Livewire\Livewire;

uses(RefreshDatabase::class);

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

test('restore run wizard blocks execution when confirmations are missing', function () {
    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-1',
        'name' => 'ManagedEnvironment One',
        'metadata' => [],
        'rbac_status' => 'ok',
        'rbac_last_checked_at' => now(),
    ]);

    ensureDefaultProviderConnection($tenant, 'microsoft');
    spec283SeedRequirementRows($tenant, ['permissions.intune_configuration', 'permissions.intune_rbac_assignments']);

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'policy-1',
        'policy_type' => 'deviceConfiguration',
        'display_name' => 'Device Config Policy',
        'platform' => 'windows',
    ]);

    $backupSet = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => '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' => 'Backup Policy',
        ],
    ]);

    $user = User::factory()->create([
        'email' => 'tester@example.com',
        'name' => 'Tester',
    ]);
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, user: $user, role: 'owner');
    $this->actingAs($user);
    setAdminPanelContext($tenant);

    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,
        ])
        ->call('create')
        ->assertHasFormErrors(['acknowledged_impact', 'tenant_confirm']);

    expect(RestoreRun::count())->toBe(0);
});

test('restore run wizard queues execution when gates are satisfied', function () {
    Bus::fake();

    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-2',
        'name' => 'ManagedEnvironment Two',
        'metadata' => [],
        'rbac_status' => 'ok',
        'rbac_last_checked_at' => now(),
    ]);

    ensureDefaultProviderConnection($tenant, 'microsoft');
    spec283SeedRequirementRows($tenant, ['permissions.intune_configuration', 'permissions.intune_rbac_assignments']);

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'policy-2',
        'policy_type' => 'deviceConfiguration',
        'display_name' => 'Device Config Policy',
        'platform' => 'windows',
    ]);

    $backupSet = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => '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' => 'Backup Policy',
        ],
    ]);

    $user = User::factory()->create([
        'email' => 'executor@example.com',
        'name' => 'Executor',
    ]);
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, user: $user, role: 'owner');
    $this->actingAs($user);
    setAdminPanelContext($tenant);

    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' => 'ManagedEnvironment Two',
        ])
        ->call('create')
        ->assertHasNoFormErrors();

    $run = RestoreRun::query()->latest('id')->first();

    expect($run)->not->toBeNull();
    expect($run->status)->toBe(RestoreRunStatus::Queued->value);
    expect($run->is_dry_run)->toBeFalse();
    expect($run->metadata['confirmed_by'] ?? null)->toBe('executor@example.com');
    expect($run->metadata['confirmed_at'] ?? null)->toBeString();

    $operationRun = OperationRun::query()
        ->where('managed_environment_id', $tenant->id)
        ->where('type', 'restore.execute')
        ->latest('id')
        ->first();

    expect($operationRun)->not->toBeNull();
    expect($operationRun?->status)->toBe('queued');
    expect((int) ($operationRun?->context['restore_run_id'] ?? 0))->toBe((int) $run->getKey());
    expect($operationRun?->context['provider_connection_id'] ?? null)->toBeInt();
    expect((int) ($run->refresh()->operation_run_id ?? 0))->toBe((int) ($operationRun?->getKey() ?? 0));

    Bus::assertDispatched(ExecuteRestoreRunJob::class, function (ExecuteRestoreRunJob $job) use ($run, $operationRun): bool {
        return $job->restoreRunId === (int) $run->getKey()
            && $job->providerConnectionId === ($operationRun?->context['provider_connection_id'] ?? null)
            && $job->operationRun instanceof OperationRun
            && $job->operationRun->getKey() === $operationRun?->getKey();
    });
});

test('restore run wizard blocks execution when scope drift invalidates preview and checks evidence', function () {
    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-3',
        'name' => 'ManagedEnvironment Three',
        'metadata' => [],
        'rbac_status' => 'ok',
        'rbac_last_checked_at' => now(),
    ]);

    ensureDefaultProviderConnection($tenant, 'microsoft');
    spec283SeedRequirementRows($tenant, ['permissions.intune_configuration', 'permissions.intune_rbac_assignments']);

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'policy-3',
        'policy_type' => 'deviceConfiguration',
        'display_name' => 'Device Config Policy',
        'platform' => 'windows',
    ]);

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

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

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

    $user = User::factory()->create([
        'email' => 'drift@example.com',
        'name' => 'Drift Tester',
    ]);
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, user: $user, role: 'owner');
    $this->actingAs($user);
    setAdminPanelContext($tenant);

    Livewire::test(CreateRestoreRun::class)
        ->fillForm([
            'backup_set_id' => $backupSet->id,
        ])
        ->goToNextWizardStep()
        ->fillForm([
            'scope_mode' => 'selected',
            'backup_item_ids' => [$firstItem->id],
        ])
        ->goToNextWizardStep()
        ->callFormComponentAction('check_results', 'run_restore_checks')
        ->goToNextWizardStep()
        ->callFormComponentAction('preview_diffs', 'run_restore_preview')
        ->goToPreviousWizardStep()
        ->goToPreviousWizardStep()
        ->fillForm([
            'backup_item_ids' => [$secondItem->id],
        ])
        ->goToWizardStep(5)
        ->fillForm([
            'is_dry_run' => false,
            'acknowledged_impact' => true,
            'tenant_confirm' => 'ManagedEnvironment Three',
        ])
        ->call('create');

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

test('admin restore run wizard ignores prefill query params for backup sets outside the canonical tenant', function () {
    $tenantA = ManagedEnvironment::factory()->create([
        'name' => 'Phoenicon',
        'environment' => 'dev',
    ]);
    [$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');

    $tenantB = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $tenantA->workspace_id,
        'name' => 'YPTW2',
        'environment' => 'dev',
    ]);

    createUserWithTenant(tenant: $tenantB, user: $user, role: 'owner');

    $policy = Policy::factory()->for($tenantB)->create([
        'external_id' => 'policy-admin-prefill-wrong-tenant',
    ]);

    $backupSet = BackupSet::factory()->for($tenantB)->create([
        'status' => 'completed',
        'item_count' => 1,
    ]);

    $backupItem = BackupItem::factory()->for($tenantB)->for($backupSet)->for($policy)->create();

    $this->actingAs($user);
    setAdminPanelContext();

    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenantA->workspace_id);
    session()->put(WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY, [
        (string) $tenantA->workspace_id => (int) $tenantA->getKey(),
    ]);

    $component = Livewire::withQueryParams([
        'backup_set_id' => $backupSet->id,
        'scope_mode' => 'selected',
        'backup_item_ids' => [$backupItem->id],
    ])->test(CreateRestoreRun::class);

    expect($component->get('data.backup_set_id'))->toBeNull();
    expect($component->get('data.scope_mode'))->not->toBe('selected');
    expect($component->get('data.backup_item_ids'))->toBe([]);
});
