"""Verify view"""

# Utils
import json

import requests

# Django
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_GET


@require_GET
def verify_account(request):
    # Get token from URL parameters
    token = request.GET.get("token")

    if not token:
        return JsonResponse({"error": "Token is required"}, status=400)

    # API endpoint
    api_url = f"http://{request.get_host()}/api/users/verify/"

    # Prepare the request
    headers = {"Content-Type": "application/json"}
    data = {"token": token}

    try:
        # Make POST request to API
        response = requests.post(api_url, headers=headers, data=json.dumps(data))

        # Check response
        if response.status_code == 200:
            # If verification successful, redirect to success page
            return render(request, "users/verification_success.html")
        else:
            # If verification failed, show error
            error_data = response.json()
            return render(
                request,
                "users/verification_error.html",
                {"error": error_data.get("token", ["Verification failed"])[0]},
            )

    except requests.RequestException as e:
        return render(
            request,
            "users/verification_error.html",
            {"error": "Connection error occurred"},
        )
