<?php

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

uses(RefreshDatabase::class);

test('restore selection options are grouped and preserve provider-missing continuity', function () {
    $tenant = ManagedEnvironment::factory()->create(['status' => 'active']);

    $policy = Policy::factory()->create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'policy-1',
        'policy_type' => 'settingsCatalogPolicy',
        'display_name' => 'Policy Display',
        'platform' => 'windows',
    ]);
    $previewOnlyPolicy = Policy::factory()->create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'policy-preview-only',
        'policy_type' => 'conditionalAccessPolicy',
        'display_name' => 'Conditional Access Policy',
        'platform' => 'all',
    ]);
    $ignoredPolicy = Policy::factory()->create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'policy-ignored',
        'policy_type' => 'deviceCompliancePolicy',
        'display_name' => 'Ignored Policy',
        'platform' => 'windows',
        'ignored_at' => now(),
    ]);
    $providerMissingPolicy = Policy::factory()->create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'policy-provider-missing',
        'policy_type' => 'deviceCompliancePolicy',
        'display_name' => 'Provider Missing Policy',
        'platform' => 'windows',
        'missing_from_provider_at' => now(),
    ]);
    $combinedPolicy = Policy::factory()->create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'policy-ignored-provider-missing',
        'policy_type' => 'deviceCompliancePolicy',
        'display_name' => 'Ignored Provider Missing Policy',
        'platform' => 'windows',
        'ignored_at' => now(),
        'missing_from_provider_at' => now(),
    ]);

    $backupSet = BackupSet::factory()->for($tenant)->create([
        'item_count' => 6,
    ]);

    $policyItem = BackupItem::factory()
        ->for($tenant)
        ->for($backupSet)
        ->state([
            'policy_id' => $policy->id,
            'policy_identifier' => $policy->external_id,
            'policy_type' => $policy->policy_type,
            'platform' => $policy->platform,
            'payload' => ['id' => $policy->external_id],
        ])
        ->create();

    $ignoredPolicyItem = BackupItem::factory()
        ->for($tenant)
        ->for($backupSet)
        ->state([
            'policy_id' => $ignoredPolicy->id,
            'policy_identifier' => $ignoredPolicy->external_id,
            'policy_type' => $ignoredPolicy->policy_type,
            'platform' => $ignoredPolicy->platform,
            'payload' => ['id' => $ignoredPolicy->external_id],
        ])
        ->create();

    $providerMissingItem = BackupItem::factory()
        ->for($tenant)
        ->for($backupSet)
        ->state([
            'policy_id' => $providerMissingPolicy->id,
            'policy_identifier' => $providerMissingPolicy->external_id,
            'policy_type' => $providerMissingPolicy->policy_type,
            'platform' => $providerMissingPolicy->platform,
            'payload' => ['id' => $providerMissingPolicy->external_id],
        ])
        ->create();

    $combinedItem = BackupItem::factory()
        ->for($tenant)
        ->for($backupSet)
        ->state([
            'policy_id' => $combinedPolicy->id,
            'policy_identifier' => $combinedPolicy->external_id,
            'policy_type' => $combinedPolicy->policy_type,
            'platform' => $combinedPolicy->platform,
            'payload' => ['id' => $combinedPolicy->external_id],
        ])
        ->create();

    $scopeTagItem = BackupItem::factory()
        ->for($tenant)
        ->for($backupSet)
        ->state([
            'policy_id' => null,
            'policy_identifier' => 'tag-1',
            'policy_type' => 'roleScopeTag',
            'platform' => 'all',
            'payload' => [
                'id' => 'tag-1',
                'displayName' => 'Scope Tag Alpha',
            ],
            'metadata' => [
                'displayName' => 'Scope Tag Alpha',
            ],
        ])
        ->create();

    $previewOnlyItem = BackupItem::factory()
        ->for($tenant)
        ->for($backupSet)
        ->state([
            'policy_id' => $previewOnlyPolicy->id,
            'policy_identifier' => $previewOnlyPolicy->external_id,
            'policy_type' => $previewOnlyPolicy->policy_type,
            'platform' => $previewOnlyPolicy->platform,
            'payload' => ['id' => $previewOnlyPolicy->external_id],
        ])
        ->create();

    $user = User::factory()->create();
    [$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',
        ])
        ->assertFormFieldVisible('backup_item_ids')
        ->assertSee('Include foundations');

    $method = new ReflectionMethod(RestoreRunResource::class, 'restoreItemGroupedOptions');
    $method->setAccessible(true);

    $groupedOptions = $method->invoke(null, $backupSet->id);

    expect($groupedOptions)->toHaveKey('Configuration • Settings Catalog Policy • windows');
    expect($groupedOptions)->toHaveKey('Foundations • Scope Tag • all');
    expect($groupedOptions)->toHaveKey('Conditional Access • Conditional Access • all • preview-only');

    $flattenedOptions = collect($groupedOptions)
        ->reduce(fn (array $carry, array $options): array => $carry + $options, []);

    expect($flattenedOptions)->toHaveKey($policyItem->id);
    expect($flattenedOptions[$policyItem->id])->toContain('Policy Display')
        ->and($flattenedOptions[$policyItem->id])->toContain('Full payload');

    expect($flattenedOptions)->not->toHaveKey($ignoredPolicyItem->id);

    expect($flattenedOptions)->toHaveKey($providerMissingItem->id);
    expect($flattenedOptions[$providerMissingItem->id])->toContain('Provider Missing Policy')
        ->and($flattenedOptions[$providerMissingItem->id])->toContain('provider missing now');

    expect($flattenedOptions)->toHaveKey($combinedItem->id);
    expect($flattenedOptions[$combinedItem->id])->toContain('Ignored Provider Missing Policy')
        ->and($flattenedOptions[$combinedItem->id])->toContain('provider missing now');

    expect($flattenedOptions)->toHaveKey($scopeTagItem->id);
    expect($flattenedOptions[$scopeTagItem->id])->toContain('Scope Tag Alpha');

    expect($flattenedOptions)->toHaveKey($previewOnlyItem->id);
    expect($flattenedOptions[$previewOnlyItem->id])->toContain('Conditional Access Policy')
        ->and($flattenedOptions[$previewOnlyItem->id])->toContain('Full payload');
});
