"""Password views."""

# Utils
import json

import requests

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

# Forms
from {{project_slug}}.users.forms import ResetPasswordForm


@require_http_methods(["GET", "POST"])
def reset_password(request):
    token = request.GET.get("token")

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

    if request.method == "POST":
        form = ResetPasswordForm(request.POST)
        if form.is_valid():
            try:
                # Enviar a la API
                api_url = f"http://{request.get_host()}/api/users/reset-password/"
                headers = {"Content-Type": "application/json"}
                data = {
                    "token": token,
                    "password": form.cleaned_data["password"],
                    "password_confirmation": form.cleaned_data["password_confirmation"],
                }

                response = requests.post(
                    api_url, headers=headers, data=json.dumps(data)
                )

                if response.status_code == 200:
                    return render(request, "users/reset_password_success.html")

                error_data = response.json()
                form.add_error(
                    None,
                    error_data.get("token", ["Error al restablecer la contraseña"])[0],
                )

            except requests.RequestException:
                form.add_error(None, "Error de conexión")
    else:
        form = ResetPasswordForm()

    return render(request, "users/reset_password.html", {"form": form, "token": token})
