<?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\Tenant;
use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

test('restore selection options are grouped and filter ignored policies', function () {
    $tenant = Tenant::factory()->create(['status' => 'active']);
    $tenant->makeCurrent();

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

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

    $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();

    $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();
    $this->actingAs($user);
    $user->tenants()->syncWithoutDetaching([
        $tenant->getKey() => ['role' => 'owner'],
    ]);
    Filament::setTenant($tenant, true);

    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])->toBe('Policy Display');

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

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

    expect($flattenedOptions)->toHaveKey($previewOnlyItem->id);
    expect($flattenedOptions[$previewOnlyItem->id])->toBe('Conditional Access Policy');
});
