<?php

namespace Tests\Feature;

use App\Models\Backup;
use App\Models\SystemSetting;
use App\Models\User;
use App\Models\Website;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class OperationsFlowTest extends TestCase
{
    use RefreshDatabase;

    public function test_super_admin_can_update_settings(): void
    {
        $user = User::factory()->superAdmin()->create();
        $setting = SystemSetting::query()->create([
            'group' => 'Security',
            'key' => 'emergency_lock_mode',
            'label' => 'Emergency Lock Mode',
            'type' => 'boolean',
            'value' => '0',
            'description' => 'Temporarily block new logins.',
        ]);

        $this->actingAs($user)
            ->put(route('settings.update'), [
                'settings' => [
                    $setting->id => '1',
                ],
            ])
            ->assertRedirect();

        $this->assertDatabaseHas('system_settings', [
            'id' => $setting->id,
            'value' => '1',
        ]);
    }

    public function test_super_admin_can_queue_and_delete_backup_records(): void
    {
        Storage::fake('local');
        Http::fake([
            '*' => Http::response([
                'status' => 'completed',
                'storage_disk' => 'local',
                'file_path' => 'backups/test.zip',
                'checksum' => sha1('demo'),
                'size_bytes' => 4,
                'completed_at' => now()->toIso8601String(),
            ], 201),
        ]);

        $user = User::factory()->superAdmin()->create();
        $website = Website::factory()->for($user, 'createdBy')->create();
        $website->agent()->create([
            'status' => 'online',
            'authentication_status' => 'verified',
            'sync_status' => 'synced',
        ]);

        $this->actingAs($user)
            ->post(route('backups.store', $website))
            ->assertRedirect();

        $backup = Backup::query()->latest('id')->first();

        $this->assertNotNull($backup);
        $this->assertSame('completed', $backup->status);

        Storage::disk('local')->put('backups/test.zip', 'demo');

        $this->actingAs($user)
            ->delete(route('backups.destroy', $backup))
            ->assertRedirect();

        $this->assertDatabaseMissing('backups', ['id' => $backup->id]);
        Storage::disk('local')->assertMissing('backups/test.zip');
    }

    public function test_backup_restore_stays_deferred_in_phase_one(): void
    {
        $user = User::factory()->superAdmin()->create();
        $website = Website::factory()->for($user, 'createdBy')->create();
        $backup = Backup::factory()->for($website)->for($user, 'initiatedBy')->create([
            'status' => 'completed',
        ]);

        $this->actingAs($user)
            ->post(route('backups.restore', $backup))
            ->assertRedirect()
            ->assertSessionHas('error', 'Backup restore is intentionally deferred until Phase 2.');

        $backup->refresh();

        $this->assertSame('completed', $backup->status);
        $this->assertNull($backup->restored_at);
    }

    public function test_super_admin_can_sync_a_website_successfully(): void
    {
        Http::fake([
            'https://demo.example.com/agent/health' => Http::response([
                'status' => 'online',
                'health' => 'healthy',
                'version' => 'v2.1.0',
                'database_count' => 3,
                'table_count' => 48,
                'capabilities' => ['health', 'tables', 'backups'],
            ], 200),
            'https://demo.example.com/agent/tables' => Http::response([
                'tables' => [
                    [
                        'table_name' => 'users',
                        'row_count' => 12,
                        'size_bytes' => 4096,
                        'last_updated_at' => now()->toIso8601String(),
                        'structure' => ['columns' => [['name' => 'id', 'type' => 'bigint']]],
                    ],
                    [
                        'table_name' => 'activity_logs',
                        'row_count' => 44,
                        'size_bytes' => 16384,
                        'last_updated_at' => now()->toIso8601String(),
                        'structure' => ['columns' => [['name' => 'id', 'type' => 'bigint']]],
                    ],
                ],
            ], 200),
        ]);

        $user = User::factory()->superAdmin()->create();
        $website = Website::factory()->for($user, 'createdBy')->create([
            'domain' => 'demo.example.com',
            'api_endpoint' => 'https://demo.example.com/agent',
            'status' => 'pending',
            'health_status' => 'unknown',
        ]);

        $website->agent()->create([
            'status' => 'pending',
            'authentication_status' => 'pending',
            'sync_status' => 'pending',
        ]);

        $this->actingAs($user)
            ->post(route('websites.sync', $website))
            ->assertRedirect();

        $website->refresh();

        $this->assertSame('online', $website->status);
        $this->assertSame('healthy', $website->health_status);
        $this->assertSame(3, $website->database_count);
        $this->assertSame(2, $website->table_count);
        $this->assertSame('v2.1.0', $website->agent->version);
        $this->assertSame('synced', $website->agent->sync_status);
        $this->assertDatabaseHas('table_snapshots', [
            'website_id' => $website->id,
            'table_name' => 'users',
        ]);
    }
}
