# 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, redirect
from django.contrib.auth import get_user_model
from django.contrib.auth import login
from django.utils import timezone

from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework import permissions, viewsets, status
from rest_framework.decorators import action

from django_core_micha.invitations.mixins import InviteActionsMixin
from django_core_micha.auth.roles import RolePolicy
from django_core_micha.auth.security import set_security_level

from allauth.mfa.models import Authenticator

from .recovery import RecoveryRequest
from .serializers import RecoveryRequestSerializer
from .permissions import IsSupportAgent, IsAssignedSupportOrAdmin
from .security import create_recovery_request_for_user

from rest_framework.views import APIView
from django.utils.translation import gettext_lazy as _

from django_core_micha.auth.roles import get_role_level_for_user, ROLE_LEVEL_3
from django.conf import settings
from django.core.mail import send_mail


User = get_user_model()

def _notify_support_about_recovery_request(rr: RecoveryRequest, support_contact):
    """
    Very small default notification helper.
    Projects can override completely by ignoring this and
    implementing their own logic (signals, celery, etc.).
    """
    subject = "[Security] MFA recovery requested"
    user_email = rr.user.email or rr.user.username
    msg_lines = [
        f"A MFA recovery request has been created for user: {user_email}",
        f"Request ID: {rr.id}",
        "",
        "You can generate a recovery login link from the Support tab.",
    ]
    message = "\n".join(msg_lines)

    # 1) Send to assigned support_contact, if present
    recipients = []
    if support_contact and support_contact.email:
        recipients.append(support_contact.email)

    # 2) Optional: global fallback
    fallback_email = getattr(settings, "SUPPORT_FALLBACK_EMAIL", None)
    if fallback_email:
        recipients.append(fallback_email)

    if recipients:
        send_mail(
            subject,
            message,
            getattr(settings, "DEFAULT_FROM_EMAIL", None),
            recipients,
            fail_silently=True,
        )

def can_manage_recovery_for(target_user, acting_user) -> bool:
    """
    Simple default policy:
    - superuser: always yes
    - if target_user.profile.support_contact == acting_user: yes
    - else: check role level against SUPPORT_ASSIGN_ROLE_LEVEL
    """
    if not acting_user or not acting_user.is_authenticated:
        return False
    if acting_user.is_superuser:
        return True

    profile = getattr(target_user, "profile", None)
    support_contact = getattr(profile, "support_contact", None)
    if support_contact and support_contact == acting_user:
        return True

    from django_core_micha.auth.roles import get_role_level_for_user, ROLE_LEVEL_3
    from django.conf import settings

    min_level = getattr(settings, "SUPPORT_ASSIGN_ROLE_LEVEL", ROLE_LEVEL_3)
    return get_role_level_for_user(acting_user) >= int(min_level)

def recovery_complete_view(request, token: str):
    """
    One-time landing page for MFA recovery links.
    Logs the user in at 'recovery' level and redirects to the Security tab.
    """
    rr = get_object_or_404(RecoveryRequest, token=token)

    # Nur aktive Requests akzeptieren
    if not rr.is_active():
        # Optional: eine nette Fehlermeldung / Seite
        return redirect(f"{settings.PUBLIC_ORIGIN}/login?recovery=expired")

    user = rr.user

    # Klassisch einloggen
    login(request, user, backend="django.contrib.auth.backends.ModelBackend")

    # Security-Level setzen
    set_security_level(request, "recovery")

    # Request final markieren (Status: completed)
    rr.mark_completed()

    # Redirect ins Frontend, Security-Tab mit from=recovery
    target = f"{settings.PUBLIC_ORIGIN}/account?tab=security&from=recovery"
    return redirect(target)


class BaseUserViewSet(InviteActionsMixin, viewsets.ModelViewSet):
    """
    Core User API:
    - list/retrieve/update/delete: authenticated users
    - current: get/patch self
    - update-role: role management via RolePolicy
    """

    queryset = User.objects.all()
    serializer_class = None  # must be set in project
    permission_classes = [IsAuthenticated]
    role_policy_class = RolePolicy

    def get_role_policy(self):
        return self.role_policy_class()

    @action(
        detail=False,
        methods=["get", "patch"],
        permission_classes=[IsAuthenticated],
        url_path="current",
    )
    def current(self, request):
        if request.method == "GET":
            serializer = self.get_serializer(request.user)
            return Response(serializer.data)

        serializer = self.get_serializer(
            request.user, data=request.data, partial=True
        )
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(
        detail=True,
        methods=["patch"],
        permission_classes=[permissions.IsAuthenticated],
        url_path="update-role",
    )
    def update_role(self, request, pk=None):
        user = self.get_object()
        new_role = request.data.get("role")

        policy = self.get_role_policy()

        if not policy.is_valid_code(new_role):
            return Response(
                {"detail": "Invalid role."},
                status=400,
            )

        if not policy.can_change_role(request.user, user, new_role):
            return Response({"detail": "Permission denied."}, status=403)

        user.profile.role = new_role
        user.profile.save()
        return Response({"detail": "Role updated successfully."})
    
    @action(
        detail=False,
        methods=["post"],
        permission_classes=[AllowAny],
        url_path="mfa/support-help",
    )
    def mfa_support_help(self, request):
        """
        Called when the user clicks "I can't use any of these methods"
        on the MFA step. We do NOT require authentication here.
        The client sends an identifier (usually the e-mail).
        """
        identifier = request.data.get("email") or request.data.get("identifier")
        message = request.data.get("message", "")

        if not identifier:
            return Response(
                {"detail": _("Email or identifier is required.")},
                status=status.HTTP_400_BAD_REQUEST,
            )

        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email__iexact=identifier)
        except UserModel.DoesNotExist:
            # Do not leak whether the account exists.
            return Response(
                {"detail": _("If this account exists, support has been notified.")},
                status=status.HTTP_200_OK,
            )

        rr = RecoveryRequest.objects.create(user=user, message=message)

        # Try to find the assigned supporter on the profile (project-specific field)
        profile = getattr(user, "profile", None)
        support_contact = getattr(profile, "support_contact", None)

        # Optional: fallback – e.g. all level >= SUPPORT_ASSIGN_ROLE_LEVEL
        # (nur wenn kein support_contact gesetzt ist)
        if support_contact is None:
            min_level = getattr(settings, "SUPPORT_ASSIGN_ROLE_LEVEL", ROLE_LEVEL_3)
            # Hier könntest du z. B. alle User mit ausreichendem Level holen
            # In der Minimal-Version: einfach None lassen oder globalen Mail-Empfänger nutzen.
            support_contact = None

        # Optional: simple notification via e-mail (project can override)
        try:
            _notify_support_about_recovery_request(rr, support_contact)
        except Exception:
            # Nicht den Flow sprengen, wenn Mail fehlschlägt
            pass

        return Response(
            {"detail": _("If this account exists, support has been notified.")},
            status=status.HTTP_200_OK,
        )

    @action(
        detail=True,
        methods=["post"],
        permission_classes=[IsAuthenticated],
        url_path="mfa/support-generate-link",
    )
    def mfa_support_generate_link(self, request, pk=None):
        """
        Support action: generate a one-time recovery login link for the target user.
        Returns the link so the supporter can send it via their preferred channel.
        """
        user = self.get_object()

        if not can_manage_recovery_for(user, request.user):
            return Response(
                {"detail": "Permission denied."},
                status=status.HTTP_403_FORBIDDEN,
            )

        # Erzeuge oder verwende frische RecoveryRequest
        rr = RecoveryRequest.objects.create(user=user)

        # Build the absolute recovery URL
        path = reverse("mfa-recovery-complete", args=[rr.token])
        recovery_url = request.build_absolute_uri(path)

        # Mark as "link sent" (resolved_by = supporter)
        rr.mark_link_sent(request.user)

        return Response({"recovery_link": recovery_url}, status=status.HTTP_200_OK)


@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 RecoveryRequestViewSet(viewsets.ModelViewSet):
    """
    API for listing/handling recovery requests (support side) and
    creating a request from MFA-flow (user side).
    """

    queryset = RecoveryRequest.objects.all().select_related("user", "resolved_by")
    serializer_class = RecoveryRequestSerializer

    def get_permissions(self):
        if self.action == "create_from_mfa":
            return [permissions.IsAuthenticated()]
        if self.action in ("list", "retrieve"):
            return [IsSupportAgent()]
        if self.action in ("approve", "reject"):
            return [IsAssignedSupportOrAdmin()]
        return super().get_permissions()

    def get_queryset(self):
        qs = super().get_queryset()
        status_param = self.request.query_params.get("status")
        if status_param:
            qs = qs.filter(status=status_param)
        return qs


    @action(methods=["post"], detail=True)
    def approve(self, request, pk=None):
        rr = self.get_object()

        if not IsAssignedSupportOrAdmin().has_object_permission(request, self, rr):
            return Response({"detail": "Permission denied."}, status=status.HTTP_403_FORBIDDEN)

        # Link bauen
        path = reverse("mfa-recovery-complete", args=[rr.token])
        recovery_url = request.build_absolute_uri(path)

        rr.mark_resolved(RecoveryRequest.Status.APPROVED, by=request.user)

        serializer = self.get_serializer(rr)
        data = serializer.data
        data["recovery_link"] = recovery_url
        return Response(data)

    @action(methods=["post"], detail=True)
    def reject(self, request, pk=None):
        rr = self.get_object()
        rr.mark_resolved(RecoveryRequest.Status.REJECTED, by=request.user)
        serializer = self.get_serializer(rr)
        return Response(serializer.data)