<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\VpnService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class VpnController extends Controller
{
    public function __construct(protected VpnService $vpnService)
    {
    }

    public function servers(): JsonResponse
    {
        $servers = $this->vpnService->getServers();

        return response()->json([
            'status' => 'success',
            'servers' => $servers,
        ]);
    }

    public function connect(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'server_id' => 'required|exists:vpn_servers,id',
            'protocol' => 'nullable|string|in:WireGuard,OpenVPN,IKeV2',
        ]);

        $connection = $this->vpnService->connect(
            $request->user(),
            $validated['server_id'],
            $validated['protocol'] ?? 'WireGuard'
        );

        return response()->json([
            'status' => 'success',
            'message' => 'VPN Connected Successfully',
            'connection' => $connection->load('server'),
        ]);
    }

    public function disconnect(Request $request): JsonResponse
    {
        $connection = $this->vpnService->disconnect($request->user());

        return response()->json([
            'status' => 'success',
            'message' => 'VPN Disconnected',
            'connection' => $connection,
        ]);
    }

    public function activeSession(Request $request): JsonResponse
    {
        $session = $this->vpnService->getActiveSession($request->user());

        return response()->json([
            'status' => 'success',
            'session' => $session,
        ]);
    }

    public function history(Request $request): JsonResponse
    {
        $history = $this->vpnService->getHistory($request->user());

        return response()->json([
            'status' => 'success',
            'history' => $history,
        ]);
    }
}
