<?php

namespace App\Services;

use App\Models\User;
use App\Models\VpnConnection;
use App\Models\VpnServer;
use Carbon\Carbon;

class VpnService
{
    public function getServers()
    {
        return VpnServer::where('is_active', true)
            ->orderBy('is_premium', 'asc')
            ->orderBy('latency_ms', 'asc')
            ->get();
    }

    public function connect(User $user, int $serverId, string $protocol = 'WireGuard'): VpnConnection
    {
        // Disconnect any active connection first
        $this->disconnect($user);

        $server = VpnServer::findOrFail($serverId);

        return VpnConnection::create([
            'user_id' => $user->id,
            'server_id' => $server->id,
            'protocol' => $protocol,
            'connected_at' => Carbon::now(),
            'status' => 'connected',
            'bytes_downloaded' => rand(10240, 524288),
            'bytes_uploaded' => rand(5120, 262144),
        ]);
    }

    public function disconnect(User $user): ?VpnConnection
    {
        $activeConnection = VpnConnection::where('user_id', $user->id)
            ->where('status', 'connected')
            ->first();

        if ($activeConnection) {
            $activeConnection->update([
                'disconnected_at' => Carbon::now(),
                'status' => 'disconnected',
                'bytes_downloaded' => $activeConnection->bytes_downloaded + rand(1048576, 52428800),
                'bytes_uploaded' => $activeConnection->bytes_uploaded + rand(524288, 10485760),
            ]);
        }

        return $activeConnection;
    }

    public function getActiveSession(User $user): ?VpnConnection
    {
        return VpnConnection::with('server')
            ->where('user_id', $user->id)
            ->where('status', 'connected')
            ->latest()
            ->first();
    }

    public function getHistory(User $user)
    {
        return VpnConnection::with('server')
            ->where('user_id', $user->id)
            ->orderBy('id', 'desc')
            ->take(20)
            ->get();
    }
}
