<?php

use App\Filament\Resources\BackupSetResource\Pages\ListBackupSets;
use App\Filament\Resources\PolicyResource\Pages\ListPolicies;
use App\Filament\Resources\PolicyVersionResource\Pages\ListPolicyVersions;
use App\Filament\Resources\RestoreRunResource\Pages\ListRestoreRuns;
use App\Filament\Resources\ManagedEnvironmentResource\Pages\ListManagedEnvironments;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\Policy;
use App\Models\PolicyVersion;
use App\Models\RestoreRun;
use App\Models\ManagedEnvironment;
use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

test('backup set can be archived when unused', function () {
    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-1',
        'name' => 'ManagedEnvironment',
    ]);

    $tenant->makeCurrent();

    $backupSet = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Set 1',
        'status' => 'completed',
    ]);

    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'],
    ]);

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

    Livewire::test(ListBackupSets::class)
        ->callTableAction('archive', $backupSet);

    $this->assertSoftDeleted('backup_sets', ['id' => $backupSet->id]);
    $this->assertSoftDeleted('backup_items', ['backup_set_id' => $backupSet->id]);
    $this->assertDatabaseHas('audit_logs', [
        'resource_type' => 'backup_set',
        'resource_id' => (string) $backupSet->id,
        'action' => 'backup.deleted',
    ]);
});

test('backup set can be archived when restore runs exist', function () {
    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-2',
        'name' => 'ManagedEnvironment 2',
    ]);

    $tenant->makeCurrent();

    $backupSet = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Set with restore',
        'status' => 'completed',
    ]);

    $restoreRun = RestoreRun::create([
        'managed_environment_id' => $tenant->id,
        'backup_set_id' => $backupSet->id,
        'status' => 'completed',
    ]);

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

    Livewire::test(ListBackupSets::class)
        ->callTableAction('archive', $backupSet);

    $this->assertSoftDeleted('backup_sets', ['id' => $backupSet->id]);
    $this->assertDatabaseHas('audit_logs', [
        'resource_type' => 'backup_set',
        'resource_id' => (string) $backupSet->id,
        'action' => 'backup.deleted',
    ]);
    $this->assertDatabaseHas('restore_runs', ['id' => $restoreRun->id]);
});

test('backup set can be force deleted when trashed and unused', function () {
    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-force',
        'name' => 'ManagedEnvironment Force',
    ]);

    $tenant->makeCurrent();

    $backupSet = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Set force',
        'status' => 'completed',
    ]);

    BackupItem::create([
        'managed_environment_id' => $tenant->id,
        'backup_set_id' => $backupSet->id,
        'policy_id' => null,
        'policy_identifier' => 'policy-force',
        'policy_type' => 'deviceConfiguration',
        'platform' => 'windows',
        'payload' => ['id' => 'policy-force'],
    ]);

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

    Livewire::test(ListBackupSets::class)
        ->callTableAction('archive', $backupSet)
        ->set('tableFilters.trashed.value', 1)
        ->callTableAction('forceDelete', $backupSet);

    $this->assertDatabaseMissing('backup_sets', ['id' => $backupSet->id]);
    $this->assertDatabaseMissing('backup_items', ['backup_set_id' => $backupSet->id]);
    $this->assertDatabaseHas('audit_logs', [
        'resource_type' => 'backup_set',
        'resource_id' => (string) $backupSet->id,
        'action' => 'backup.force_deleted',
    ]);
});

test('backup set can be restored when archived', function () {
    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-restore-backup-set',
        'name' => 'ManagedEnvironment Restore Backup Set',
    ]);

    $tenant->makeCurrent();

    $backupSet = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Set restore',
        'status' => 'completed',
    ]);

    BackupItem::create([
        'managed_environment_id' => $tenant->id,
        'backup_set_id' => $backupSet->id,
        'policy_id' => null,
        'policy_identifier' => 'policy-restore',
        'policy_type' => 'deviceConfiguration',
        'platform' => 'windows',
        'payload' => ['id' => 'policy-restore'],
    ]);

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

    Livewire::test(ListBackupSets::class)
        ->callTableAction('archive', $backupSet)
        ->set('tableFilters.trashed.value', 1)
        ->callTableAction('restore', $backupSet);

    $this->assertDatabaseHas('backup_sets', ['id' => $backupSet->id, 'deleted_at' => null]);
    $this->assertDatabaseHas('backup_items', ['backup_set_id' => $backupSet->id, 'deleted_at' => null]);
    $this->assertDatabaseHas('audit_logs', [
        'resource_type' => 'backup_set',
        'resource_id' => (string) $backupSet->id,
        'action' => 'backup.restored',
    ]);
});

test('restore run can be archived and force deleted', function () {
    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-restore-run',
        'name' => 'ManagedEnvironment Restore Run',
    ]);

    $tenant->makeCurrent();

    $backupSet = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Set RR',
        'status' => 'completed',
        'item_count' => 1,
    ]);

    $restoreRun = RestoreRun::create([
        'managed_environment_id' => $tenant->id,
        'backup_set_id' => $backupSet->id,
        'status' => 'completed',
        'is_dry_run' => true,
    ]);

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

    Livewire::test(ListRestoreRuns::class)
        ->callTableAction('archive', $restoreRun)
        ->set('tableFilters.trashed.value', 1)
        ->callTableAction('forceDelete', $restoreRun);

    $this->assertDatabaseMissing('restore_runs', ['id' => $restoreRun->id]);
    $this->assertDatabaseHas('audit_logs', [
        'resource_type' => 'restore_run',
        'resource_id' => (string) $restoreRun->id,
        'action' => 'restore_run.force_deleted',
    ]);
});

test('restore run can be restored when archived', function () {
    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-restore-restore-run',
        'name' => 'ManagedEnvironment Restore Restore Run',
    ]);

    $tenant->makeCurrent();

    $backupSet = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Set for restore run restore',
        'status' => 'completed',
        'item_count' => 1,
    ]);

    $restoreRun = RestoreRun::create([
        'managed_environment_id' => $tenant->id,
        'backup_set_id' => $backupSet->id,
        'status' => 'completed',
        'is_dry_run' => true,
    ]);

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

    Livewire::test(ListRestoreRuns::class)
        ->callTableAction('archive', $restoreRun)
        ->set('tableFilters.trashed.value', 1)
        ->callTableAction('restore', $restoreRun);

    $this->assertDatabaseHas('restore_runs', ['id' => $restoreRun->id, 'deleted_at' => null]);
    $this->assertDatabaseHas('audit_logs', [
        'resource_type' => 'restore_run',
        'resource_id' => (string) $restoreRun->id,
        'action' => 'restore_run.restored',
    ]);
});

test('policy can be ignored and restored via row actions', function () {
    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-policy-row-actions',
        'name' => 'ManagedEnvironment Policy Row Actions',
        'metadata' => [],
    ]);

    $tenant->makeCurrent();

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'policy-row-1',
        'policy_type' => 'deviceConfiguration',
        'display_name' => 'Row Action Policy',
        'platform' => 'windows',
        'last_synced_at' => now(),
    ]);

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

    Livewire::test(ListPolicies::class)
        ->callTableAction('ignore', $policy);

    $policy->refresh();
    expect($policy->ignored_at)->not->toBeNull();

    Livewire::test(ListPolicies::class)
        ->set('tableFilters.visibility.value', 'ignored')
        ->callTableAction('restore', $policy);

    $policy->refresh();
    expect($policy->ignored_at)->toBeNull();
});

test('policy version can be archived with audit log', function () {
    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-3',
        'name' => 'ManagedEnvironment 3',
    ]);

    $tenant->makeCurrent();

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'pol-1',
        'policy_type' => 'deviceConfiguration',
        'display_name' => 'Policy',
    ]);

    $version = PolicyVersion::create([
        'managed_environment_id' => $tenant->id,
        'policy_id' => $policy->id,
        'version_number' => 1,
        'policy_type' => 'deviceConfiguration',
        'snapshot' => ['id' => 'pol-1'],
    ]);

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

    Livewire::test(ListPolicyVersions::class)
        ->callTableAction('archive', $version);

    $this->assertSoftDeleted('policy_versions', ['id' => $version->id]);
    $this->assertDatabaseHas('audit_logs', [
        'resource_type' => 'policy_version',
        'resource_id' => (string) $version->id,
        'action' => 'policy_version.deleted',
    ]);
});

test('policy version can be force deleted when trashed', function () {
    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-3b',
        'name' => 'ManagedEnvironment 3b',
    ]);

    $tenant->makeCurrent();

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'pol-1b',
        'policy_type' => 'deviceConfiguration',
        'display_name' => 'Policy B',
    ]);

    $version = PolicyVersion::create([
        'managed_environment_id' => $tenant->id,
        'policy_id' => $policy->id,
        'version_number' => 1,
        'policy_type' => 'deviceConfiguration',
        'snapshot' => ['id' => 'pol-1b'],
    ]);

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

    Livewire::test(ListPolicyVersions::class)
        ->callTableAction('archive', $version)
        ->set('tableFilters.trashed.value', 1)
        ->callTableAction('forceDelete', $version);

    $this->assertDatabaseMissing('policy_versions', ['id' => $version->id]);
    $this->assertDatabaseHas('audit_logs', [
        'resource_type' => 'policy_version',
        'resource_id' => (string) $version->id,
        'action' => 'policy_version.force_deleted',
    ]);
});

test('tenant can be archived and hidden from default lists', function () {
    $tenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => 'tenant-4',
        'name' => 'ManagedEnvironment 4',
        'status' => 'active',
    ]);

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

    Livewire::test(ListManagedEnvironments::class)
        ->callTableAction('archive', $tenant, [
            'archive_reason' => 'Removing this tenant from the active housekeeping list.',
        ]);

    expect(ManagedEnvironment::count())->toBe(0);

    $this->assertSoftDeleted('managed_environments', ['id' => $tenant->id]);
    $this->assertDatabaseHas('audit_logs', [
        'resource_type' => 'tenant',
        'resource_id' => (string) $tenant->id,
        'action' => 'tenant.archived',
    ]);
});

test('tenant must be trashed before force delete and removes permanently', function () {
    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-5',
        'name' => 'ManagedEnvironment 5',
    ]);

    $tenant->delete();
    $tenant->forceDelete();

    $this->assertDatabaseMissing('managed_environments', ['id' => $tenant->id]);
});

test('tenant table archive filter toggles active and archived tenants', function () {
    $active = ManagedEnvironment::factory()->create([
        'managed_environment_id' => 'tenant-active',
        'name' => 'Active ManagedEnvironment',
        'status' => 'active',
    ]);

    [$user, $active] = createUserWithTenant(tenant: $active, role: 'owner');
    $this->actingAs($user);

    $archived = ManagedEnvironment::factory()->create([
        'managed_environment_id' => 'tenant-archived',
        'name' => 'Archived ManagedEnvironment',
        'status' => 'active',
        'workspace_id' => $active->workspace_id,
    ]);

    $archived->delete();

    $user->tenants()->syncWithoutDetaching([
        $archived->getKey() => ['role' => 'owner'],
    ]);
    setAdminPanelContext($active);

    $this->withSession([
        \App\Support\Workspaces\WorkspaceContext::SESSION_KEY => (int) $active->workspace_id,
    ]);
    session([
        \App\Support\Workspaces\WorkspaceContext::SESSION_KEY => (int) $active->workspace_id,
    ]);

    $component = Livewire::actingAs($user)
        ->test(ListManagedEnvironments::class)
        ->filterTable('trashed', true)
        ->assertSee($active->name)
        ->assertSee($archived->name);

    $component
        ->filterTable('trashed', null)
        ->assertSee($active->name)
        ->assertDontSee($archived->name);

    $component
        ->filterTable('trashed', false)
        ->assertSee($archived->name)
        ->assertDontSee($active->name);
});

test('archived tenant can be restored from the table', function () {
    $contextTenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => 'tenant-restore-context',
        'name' => 'Restore Context ManagedEnvironment',
        'status' => 'active',
    ]);

    [$user, $contextTenant] = createUserWithTenant(tenant: $contextTenant, role: 'owner');
    $this->actingAs($user);

    $tenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => 'tenant-restore',
        'name' => 'Restore ManagedEnvironment',
        'status' => 'active',
        'workspace_id' => $contextTenant->workspace_id,
    ]);

    $tenant->delete();
    $user->tenants()->syncWithoutDetaching([
        $tenant->getKey() => ['role' => 'owner'],
    ]);
    setAdminPanelContext($contextTenant);

    $this->withSession([
        \App\Support\Workspaces\WorkspaceContext::SESSION_KEY => (int) $contextTenant->workspace_id,
    ]);
    session([
        \App\Support\Workspaces\WorkspaceContext::SESSION_KEY => (int) $contextTenant->workspace_id,
    ]);

    Livewire::actingAs($user)
        ->test(ListManagedEnvironments::class)
        ->filterTable('trashed', false)
        ->callTableAction('restore', $tenant);

    $this->assertDatabaseHas('managed_environments', [
        'id' => $tenant->id,
        'deleted_at' => null,
        'lifecycle_status' => 'active',
    ]);

    $this->assertDatabaseHas('audit_logs', [
        'resource_type' => 'tenant',
        'resource_id' => (string) $tenant->id,
        'action' => 'tenant.restored',
    ]);
});
