<?php

declare(strict_types=1);

use App\Filament\Resources\BackupSetResource\Pages\EditBackupSet;
use App\Filament\Resources\BackupSetResource\RelationManagers\BackupItemsRelationManager;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\Policy;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

function backupItemsRelationManagerComponent(BackupSet $backupSet)
{
    return Livewire::test(BackupItemsRelationManager::class, [
        'ownerRecord' => $backupSet,
        'pageClass' => EditBackupSet::class,
    ]);
}

it('filters backup items by type, restore mode, and platform inside the current backup set', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $this->actingAs($user);
    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    $backupSet = BackupSet::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
    ]);

    $otherBackupSet = BackupSet::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
    ]);

    $roleDefinition = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => 'role-definition',
        'policy_type' => 'intuneRoleDefinition',
        'display_name' => 'Application Manager',
        'platform' => 'all',
    ]);

    $roleAssignment = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => 'role-assignment',
        'policy_type' => 'intuneRoleAssignment',
        'display_name' => 'TenantPilot Assignment',
        'platform' => 'all',
    ]);

    $settingsCatalog = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => 'settings-policy',
        'policy_type' => 'settingsCatalogPolicy',
        'display_name' => 'Windows Hardening',
        'platform' => 'windows',
    ]);

    $matching = BackupItem::factory()->for($backupSet)->for($tenant)->create([
        'policy_id' => (int) $roleDefinition->getKey(),
        'policy_identifier' => 'role-definition',
        'policy_type' => 'intuneRoleDefinition',
        'platform' => 'all',
        'metadata' => ['displayName' => 'Application Manager'],
    ]);

    $wrongType = BackupItem::factory()->for($backupSet)->for($tenant)->create([
        'policy_id' => (int) $roleAssignment->getKey(),
        'policy_identifier' => 'role-assignment',
        'policy_type' => 'intuneRoleAssignment',
        'platform' => 'all',
        'metadata' => ['displayName' => 'TenantPilot Assignment'],
    ]);

    $wrongRestoreMode = BackupItem::factory()->for($backupSet)->for($tenant)->create([
        'policy_id' => (int) $settingsCatalog->getKey(),
        'policy_identifier' => 'settings-policy',
        'policy_type' => 'settingsCatalogPolicy',
        'platform' => 'windows',
        'metadata' => ['displayName' => 'Windows Hardening'],
    ]);

    $otherBackupSetMatch = BackupItem::factory()->for($otherBackupSet)->for($tenant)->create([
        'policy_id' => (int) $roleDefinition->getKey(),
        'policy_identifier' => 'role-definition-other',
        'policy_type' => 'intuneRoleDefinition',
        'platform' => 'all',
        'metadata' => ['displayName' => 'Application Manager Copy'],
    ]);

    backupItemsRelationManagerComponent($backupSet)
        ->filterTable('policy_type', 'intuneRoleDefinition')
        ->filterTable('restore_mode', 'preview-only')
        ->filterTable('platform', 'all')
        ->assertCanSeeTableRecords([$matching])
        ->assertCanNotSeeTableRecords([$wrongType, $wrongRestoreMode, $otherBackupSetMatch]);
});

it('clears backup item filters back to the backup-set scoped list', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $this->actingAs($user);
    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    $backupSet = BackupSet::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
    ]);

    $roleDefinition = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => 'role-definition-clear',
        'policy_type' => 'intuneRoleDefinition',
        'display_name' => 'Help Desk Operator',
        'platform' => 'all',
    ]);

    $roleAssignment = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => 'role-assignment-clear',
        'policy_type' => 'intuneRoleAssignment',
        'display_name' => 'TenantPilot Assignment',
        'platform' => 'all',
    ]);

    $definitionItem = BackupItem::factory()->for($backupSet)->for($tenant)->create([
        'policy_id' => (int) $roleDefinition->getKey(),
        'policy_identifier' => 'role-definition-clear',
        'policy_type' => 'intuneRoleDefinition',
        'platform' => 'all',
        'metadata' => ['displayName' => 'Help Desk Operator'],
    ]);

    $assignmentItem = BackupItem::factory()->for($backupSet)->for($tenant)->create([
        'policy_id' => (int) $roleAssignment->getKey(),
        'policy_identifier' => 'role-assignment-clear',
        'policy_type' => 'intuneRoleAssignment',
        'platform' => 'all',
        'metadata' => ['displayName' => 'TenantPilot Assignment'],
    ]);

    $component = backupItemsRelationManagerComponent($backupSet)
        ->filterTable('policy_type', 'intuneRoleDefinition')
        ->filterTable('platform', 'all')
        ->assertCanSeeTableRecords([$definitionItem])
        ->assertCanNotSeeTableRecords([$assignmentItem]);

    $component
        ->set('tableFilters.policy_type.value', null)
        ->set('tableFilters.platform.value', null)
        ->assertCanSeeTableRecords([$definitionItem, $assignmentItem]);
});

it('persists backup item search, sort, and filter state across remounts', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $this->actingAs($user);
    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    $backupSet = BackupSet::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
    ]);

    Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => 'role-definition-persist',
        'policy_type' => 'intuneRoleDefinition',
        'display_name' => 'Role Persistence',
        'platform' => 'all',
    ]);

    $component = backupItemsRelationManagerComponent($backupSet)
        ->searchTable('Role')
        ->call('sortTable', 'policy.display_name', 'desc')
        ->set('tableFilters.policy_type.value', 'intuneRoleDefinition');

    $instance = $component->instance();

    expect(session()->get($instance->getTableSearchSessionKey()))->toBe('Role');
    expect(session()->get($instance->getTableSortSessionKey()))->toBe('policy.display_name:desc');
    expect(data_get(session()->get($instance->getTableFiltersSessionKey()), 'policy_type.value'))->toBe('intuneRoleDefinition');

    backupItemsRelationManagerComponent($backupSet)
        ->assertSet('tableSearch', 'Role')
        ->assertSet('tableSort', 'policy.display_name:desc')
        ->assertSet('tableFilters.policy_type.value', 'intuneRoleDefinition');
});

it('shows snapshot mode and backup quality hints for backup items', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $this->actingAs($user);
    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    $backupSet = BackupSet::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
    ]);

    $policy = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => 'quality-policy',
        'policy_type' => 'settingsCatalogPolicy',
        'display_name' => 'Quality Policy',
        'platform' => 'windows',
    ]);

    BackupItem::factory()->for($backupSet)->for($tenant)->create([
        'policy_id' => (int) $policy->getKey(),
        'policy_identifier' => 'quality-policy',
        'policy_type' => 'settingsCatalogPolicy',
        'platform' => 'windows',
        'payload' => [],
        'metadata' => [
            'displayName' => 'Quality Policy',
            'source' => 'metadata_only',
            'assignment_capture_reason' => 'separate_role_assignments',
            'has_orphaned_assignments' => true,
        ],
        'assignments' => [],
    ]);

    backupItemsRelationManagerComponent($backupSet)
        ->assertSee('Snapshot')
        ->assertSee('Backup quality')
        ->assertSee('Metadata only')
        ->assertSee('Assignments captured separately')
        ->assertSee('Orphaned assignments');
});
