<?php

namespace Tests\Feature;

use App\Models\User;
use App\Models\VpnServer;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class VpnApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_public_health_endpoint()
    {
        $response = $this->getJson('/api/health');

        $response->assertStatus(200)
            ->assertJson([
                'status' => 'online',
                'app' => 'SamaceVPN Mobile API'
            ]);
    }

    public function test_user_can_register_and_login()
    {
        // Registration
        $registerResponse = $this->postJson('/api/auth/register', [
            'name' => 'Mobile Tester',
            'email' => 'tester@samacevpn.com',
            'password' => 'password123',
        ]);

        $registerResponse->assertStatus(201)
            ->assertJsonStructure(['user', 'token']);

        // Login
        $loginResponse = $this->postJson('/api/auth/login', [
            'email' => 'tester@samacevpn.com',
            'password' => 'password123',
        ]);

        $loginResponse->assertStatus(200)
            ->assertJsonStructure(['user', 'token']);
    }

    public function test_authenticated_user_can_fetch_servers_and_connect()
    {
        $user = User::factory()->create();
        $server = VpnServer::create([
            'name' => 'Test US Node',
            'city' => 'New York',
            'country' => 'United States',
            'country_code' => 'US',
            'flag_emoji' => '🇺🇸',
            'ip_address' => '1.1.1.1',
            'latency_ms' => 20,
            'load_percentage' => 15,
            'is_premium' => false,
            'is_active' => true,
        ]);

        $token = $user->createToken('test_token')->plainTextToken;

        // Fetch Servers
        $serversResponse = $this->withHeader('Authorization', 'Bearer ' . $token)
            ->getJson('/api/vpn/servers');

        $serversResponse->assertStatus(200)
            ->assertJsonStructure(['status', 'servers']);

        // Connect VPN
        $connectResponse = $this->withHeader('Authorization', 'Bearer ' . $token)
            ->postJson('/api/vpn/connect', [
                'server_id' => $server->id,
                'protocol' => 'WireGuard',
            ]);

        $connectResponse->assertStatus(200)
            ->assertJson([
                'status' => 'success',
                'message' => 'VPN Connected Successfully'
            ]);

        // Disconnect VPN
        $disconnectResponse = $this->withHeader('Authorization', 'Bearer ' . $token)
            ->postJson('/api/vpn/disconnect');

        $disconnectResponse->assertStatus(200)
            ->assertJson([
                'status' => 'success',
                'message' => 'VPN Disconnected'
            ]);
    }
}
