# 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):
    """
    Simple endpoint to set the CSRF cookie for frontend clients.
    Used by ui_core_micha (CSRF_URL = '/api/csrf/').
    """
    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="webauthn",
        )
        data = [
            {
                "id": a.pk,
                "name": a.name,
                "created_at": a.created_at,
                "last_used_at": a.last_used_at,
                "is_device_passkey": getattr(a, "is_device_passkey", None),
            }
            for a in qs
        ]
        return Response(data)

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