# webapp_management/invitations/views.py

from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
from django.utils.encoding import force_str
from django.utils.http import urlsafe_base64_decode

from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework import status

User = get_user_model()


class NonAuthenticatedPasswordResetView(APIView):
    """
    Finale Schritt des Reset-/Invite-Flows:
      - GET  → prüft, ob UID+Token gültig sind
      - POST → setzt neues Passwort (ohne eingeloggt zu sein)

    Typischer Ablauf im Frontend:
      1. User klickt Link aus Mail (z.B. /reset/<uid>/<token>/ oder /invite/<uid>/<token>/)
      2. SPA liest uid & token aus der URL
      3. SPA ruft:
         - GET  /api/.../reset/<uid>/<token>/   → "valid?" check
         - POST /api/.../reset/<uid>/<token>/   → neues Passwort setzen
    """

    permission_classes = [AllowAny]

    # Texte kannst du in einem Subclass pro Projekt überschreiben
    link_valid_message = "Reset link is valid."
    link_invalid_message = "Reset link is invalid."
    missing_password_message = "Neues Passwort wurde nicht angegeben."
    invalid_link_message = "Reset link is invalid."
    success_message = "Passwort erfolgreich geändert."

    def get_user_from_uid(self, uidb64):
        try:
            uid = force_str(urlsafe_base64_decode(uidb64))
            return User.objects.get(pk=uid)
        except Exception:
            return None

    def get(self, request, uidb64, token, *args, **kwargs):
        """
        Prüft, ob der Link (UID+Token) noch gültig ist.
        """
        user = self.get_user_from_uid(uidb64)
        if user and default_token_generator.check_token(user, token):
            return Response({"detail": self.link_valid_message})
        return Response(
            {"detail": self.link_invalid_message},
            status=status.HTTP_400_BAD_REQUEST,
        )

    def post(self, request, uidb64, token, *args, **kwargs):
        """
        Setzt das neue Passwort für den User mit UID+Token.
        """
        new_pw = request.data.get("new_password")
        if not new_pw:
            return Response(
                {"detail": self.missing_password_message},
                status=status.HTTP_400_BAD_REQUEST,
            )

        user = self.get_user_from_uid(uidb64)
        if not user:
            return Response(
                {"detail": self.invalid_link_message},
                status=status.HTTP_400_BAD_REQUEST,
            )

        if not default_token_generator.check_token(user, token):
            return Response(
                {"detail": self.link_invalid_message},
                status=status.HTTP_400_BAD_REQUEST,
            )

        user.set_password(new_pw)
        if hasattr(user, "is_active"):
            user.is_active = True
        user.save()

        return Response({"detail": self.success_message})
