# django_core_micha/auth/views.py
from django.http import JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.shortcuts import get_object_or_404
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)
