<?php

use App\Filament\Resources\RestoreRunResource\Pages\CreateRestoreRun;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\RestoreRun;
use App\Models\ManagedEnvironment;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

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

test('restore run stores wizard audit metadata and preserves it on completion', function () {
    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-1',
        'name' => 'ManagedEnvironment One',
        'metadata' => [],
        'rbac_status' => 'ok',
        'rbac_last_checked_at' => now(),
    ]);

    ensureDefaultProviderConnection($tenant, 'microsoft');

    $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' => null,
        'policy_identifier' => 'policy-1',
        'policy_type' => 'deviceConfiguration',
        'platform' => 'windows',
        'payload' => ['id' => 'policy-1'],
        'metadata' => [
            'displayName' => 'Backup Policy One',
        ],
    ]);

    $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()
        ->goToNextWizardStep()
        ->callFormComponentAction('preview_diffs', 'run_restore_preview')
        ->goToNextWizardStep()
        ->call('create')
        ->assertHasNoFormErrors();

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

    expect($run)->not->toBeNull();
    expect($run->metadata)->toHaveKeys([
        'scope_mode',
        'environment',
        'highlander_label',
        'scope_basis',
        'failed',
        'non_applied',
        'total',
        'foundations_skipped',
    ]);

    expect($run->metadata['scope_mode'])->toBe('selected');
    expect($run->metadata['environment'])->toBe('test');
    expect($run->metadata['highlander_label'])->toBe('ManagedEnvironment One');
    expect($run->metadata['scope_basis']['fingerprint'] ?? null)->toBeString();
});
