# django_core_micha/auth/views.py
from django.http import JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie
from django.shortcuts import get_object_or_404

from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView


from allauth.mfa.totp import generate_key
from allauth.mfa.adapter import get_adapter
from allauth.mfa.models import Authenticator

@ensure_csrf_cookie
def csrf_token_view(request):
    return JsonResponse({"detail": "CSRF cookie set"})


class PasskeyViewSet(viewsets.ViewSet):
    permission_classes = [IsAuthenticated]

    def list(self, request):
        qs = Authenticator.objects.filter(
            user=request.user,
            type=Authenticator.Type.WEBAUTHN,
        )

        data = []
        for a in qs:
            wrapped = a.wrap()  # liefert WebAuthn-spezifische Properties
            data.append(
                {
                    "id": a.pk,
                    # Name wird aus .data rausgezogen
                    "name": getattr(wrapped, "name", None),
                    "created_at": a.created_at,
                    "last_used_at": a.last_used_at,
                    # optional, je nach allauth-Version vorhanden
                    "is_device_passkey": getattr(
                        wrapped, "is_device_passkey", None
                    ),
                }
            )

        return Response(data)

    def destroy(self, request, pk=None):
        obj = get_object_or_404(
            Authenticator,
            pk=pk,
            user=request.user,
            type=Authenticator.Type.WEBAUTHN,
        )
        obj.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

class TOTPSetupView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # Secret erzeugen
        secret = generate_key()
        adapter = get_adapter()
        key_uri = adapter.get_totp_uri(request.user, secret)
        # Secret z. B. in Session zwischenparken
        request.session["mfa_totp_setup_secret"] = secret
        return Response({"secret": secret, "key_uri": key_uri})

    def post(self, request):
        code = request.data.get("code")
        secret = request.session.get("mfa_totp_setup_secret")
        if not secret:
            return Response({"detail": "No TOTP setup in progress."}, status=400)

        adapter = get_adapter()
        if not adapter.verify_totp(request.user, secret, code):
            return Response({"detail": "Invalid TOTP code."}, status=400)

        # Authenticator anlegen
        Authenticator.objects.create(
            user=request.user,
            type="totp",
            # ggf. name oder config speichern
        )
        # Secret aus Session entfernen
        del request.session["mfa_totp_setup_secret"]
        return Response({"detail": "TOTP activated."})