from django.conf import settings
from django.contrib import auth, messages
from django.http import Http404
from django.shortcuts import redirect
from django.urls import reverse

from .models import LoginToken
from .tasks import send_login_email_task


def send_login_email(request):
    email = request.POST["email"]
    login_token = LoginToken.objects.create(email=email)
    url = request.build_absolute_uri(
        reverse("login") + "?token=" + str(login_token.uid),
    )

    send_login_email_task.delay(email, url)
    messages.success(
        request,
        "Check your email!—there you'll find a magic login link. But hurry… it's only temporary!",
    )

    return redirect("/")

def login(request):
    if user := auth.authenticate(uid=request.GET["token"]):
        auth.login(request, user)
    else:
        messages.error(request, "Invalid login link!—please request another")
    return redirect("/")


def dev_login(request, session_key):
    """DEBUG-only: set session cookie and redirect. Used by setup_sig_session command."""
    if not settings.DEBUG:
        raise Http404
    next_url = request.GET.get("next", "/")
    response = redirect(next_url)
    response.set_cookie(settings.SESSION_COOKIE_NAME, session_key, httponly=True)
    return response
