<?php

use App\Filament\Resources\PolicyVersionResource\Pages\ListPolicyVersions;
use App\Filament\Resources\RestoreRunResource\Pages\CreateRestoreRun;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\Policy;
use App\Models\PolicyVersion;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Services\Graph\GroupResolver;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Mockery\MockInterface;

uses(RefreshDatabase::class);

test('policy version can open restore wizard via row action', function () {
    $tenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => 'tenant-policy-version-wizard',
        'name' => 'ManagedEnvironment',
        'metadata' => [],
    ]);

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

    $version = PolicyVersion::create([
        'managed_environment_id' => $tenant->id,
        'policy_id' => $policy->id,
        'version_number' => 3,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'captured_at' => now(),
        'snapshot' => [
            'id' => $policy->external_id,
            'passwordMinimumLength' => 14,
            'clientSecret' => '[REDACTED]',
        ],
        'assignments' => [['intent' => 'apply']],
        'scope_tags' => [
            'ids' => ['st-1'],
            'names' => ['Tag 1'],
        ],
        'redaction_version' => 1,
        'secret_fingerprints' => [
            'snapshot' => ['/clientSecret' => 'abc123'],
            'assignments' => [],
            'scope_tags' => [],
        ],
    ]);

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

    Livewire::test(ListPolicyVersions::class)
        ->callTableAction('restore_via_wizard', $version)
        ->assertRedirectContains('/admin/workspaces/')
        ->assertRedirectContains('/environments/'.(string) $tenant->slug.'/restore-runs/create')
        ->assertRedirectContains('backup_set_id=');

    $backupSet = BackupSet::query()->where('metadata->source', 'policy_version')->first();
    expect($backupSet)->not->toBeNull();
    expect($backupSet->managed_environment_id)->toBe($tenant->id);
    expect($backupSet->metadata['policy_version_id'] ?? null)->toBe($version->id);
    expect($backupSet->metadata['integrity_warning'] ?? null)->toContain('Protected values are intentionally hidden');

    $backupItem = BackupItem::query()->where('backup_set_id', $backupSet->id)->first();
    expect($backupItem)->not->toBeNull();
    expect($backupItem->policy_version_id)->toBe($version->id);
    expect($backupItem->policy_identifier)->toBe($policy->external_id);
    expect($backupItem->metadata['scope_tag_ids'] ?? null)->toBe(['st-1']);
    expect($backupItem->metadata['scope_tag_names'] ?? null)->toBe(['Tag 1']);
    expect($backupItem->metadata['redaction_version'] ?? null)->toBe(1);
    expect($backupItem->metadata['integrity_warning'] ?? null)->toContain('Protected values are intentionally hidden');
    expect($backupItem->metadata['protected_paths_count'] ?? null)->toBe(1);
});

test('readonly users cannot open restore wizard via policy version row action', function () {
    $tenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => 'tenant-policy-version-wizard-readonly',
        'name' => 'ManagedEnvironment',
        'metadata' => [],
    ]);

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'policy-ro-1',
        'policy_type' => 'settingsCatalogPolicy',
        'display_name' => 'Settings Catalog',
        'platform' => 'windows',
    ]);

    $version = PolicyVersion::create([
        'managed_environment_id' => $tenant->id,
        'policy_id' => $policy->id,
        'version_number' => 1,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'captured_at' => now(),
        'snapshot' => ['id' => $policy->external_id, 'displayName' => $policy->display_name],
    ]);

    $user = User::factory()->create(['email' => 'readonly@example.com']);
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, user: $user, role: 'readonly');

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

    Livewire::test(ListPolicyVersions::class)
        ->assertTableActionDisabled('restore_via_wizard', $version)
        ->assertSee('Full payload')
        ->callTableAction('restore_via_wizard', $version);

    expect(BackupSet::query()->where('metadata->source', 'policy_version')->exists())->toBeFalse();
    expect(BackupItem::query()->exists())->toBeFalse();
});

test('metadata-only versions keep quality visible while restore-via-wizard stays disabled', function () {
    $tenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => 'tenant-policy-version-wizard-quality',
        'name' => 'ManagedEnvironment',
        'metadata' => [],
    ]);

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'policy-quality',
        'policy_type' => 'settingsCatalogPolicy',
        'display_name' => 'Settings Catalog',
        'platform' => 'windows',
    ]);

    $version = PolicyVersion::create([
        'managed_environment_id' => $tenant->id,
        'policy_id' => $policy->id,
        'version_number' => 1,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'captured_at' => now(),
        'snapshot' => [],
        'metadata' => [
            'source' => 'metadata_only',
        ],
    ]);

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

    Livewire::test(ListPolicyVersions::class)
        ->assertSee('Metadata only')
        ->assertTableActionDisabled('restore_via_wizard', $version);
});

test('restore run wizard hydrates group mapping for policy version backup set', function () {
    $tenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => 'tenant-policy-version-prefill',
        'name' => 'ManagedEnvironment',
        'metadata' => [],
    ]);

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

    $version = PolicyVersion::create([
        'managed_environment_id' => $tenant->id,
        'policy_id' => $policy->id,
        'version_number' => 1,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'captured_at' => now(),
        'snapshot' => ['id' => $policy->external_id],
        'assignments' => [[
            'target' => [
                '@odata.type' => '#microsoft.graph.groupAssignmentTarget',
                'groupId' => 'source-group-1',
                'group_display_name' => 'Source Group',
            ],
            'intent' => 'apply',
        ]],
    ]);

    $backupSet = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Policy Version Restore',
        'status' => 'completed',
        'item_count' => 1,
        'completed_at' => now(),
        'metadata' => [
            'source' => 'policy_version',
            'policy_version_id' => $version->id,
        ],
    ]);

    $backupItem = BackupItem::create([
        'managed_environment_id' => $tenant->id,
        'backup_set_id' => $backupSet->id,
        'policy_id' => $policy->id,
        'policy_version_id' => $version->id,
        'policy_identifier' => $policy->external_id,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'payload' => $version->snapshot ?? [],
        'assignments' => $version->assignments,
    ]);

    $this->mock(GroupResolver::class, function (MockInterface $mock) {
        $mock->shouldReceive('resolveGroupIds')
            ->andReturnUsing(function (array $groupIds): array {
                return collect($groupIds)
                    ->mapWithKeys(fn (string $id) => [$id => [
                        'id' => $id,
                        'displayName' => null,
                        'orphaned' => true,
                    ]])
                    ->all();
            });
    });

    $user = User::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, user: $user, role: 'owner');
    $this->actingAs($user);
    setAdminPanelContext($tenant);

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

    expect((int) $component->get('data.backup_set_id'))->toBe($backupSet->id);
    expect($component->get('data.scope_mode'))->toBe('selected');
    expect(array_map('intval', $component->get('data.backup_item_ids')))->toBe([$backupItem->id]);

    $mapping = $component->get('data.group_mapping');
    expect($mapping)->toBeArray();
    expect(array_key_exists('source-group-1', $mapping))->toBeTrue();
    expect($mapping['source-group-1'])->toBeNull();

    $component
        ->goToNextWizardStep()
        ->assertFormFieldVisible('group_mapping.source-group-1');
});
