"""Admin role impersonation — powers the dashboard's Command Switcher.

POST /api/v1/users/admin/impersonate/   { "role": "RECRUITER" }

Issues real JWTs for an active demo user of the requested role, so the whole
ATS (sidebar menus, permissions, every page) behaves exactly as that role.
The frontend stashes the admin's own tokens and restores them on "Return to
Admin". Admin-only; impersonating ADMIN itself is rejected."""

import logging

from django.contrib.auth import get_user_model
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken

from core.permissions import IsAdmin
from core.responses import error_response, success_response

logger = logging.getLogger(__name__)
User = get_user_model()


class ImpersonateRoleView(APIView):
    permission_classes = [IsAdmin]

    def post(self, request):
        role = str(request.data.get("role") or "").upper().strip()
        if not role or role == "ADMIN":
            return error_response("Pass a non-admin role to impersonate.")

        target = (
            User.objects.filter(role=role, is_active=True)
            .order_by("id")
            .first()
        )
        if not target:
            return error_response(f"No active user with role {role} exists to impersonate.", status_code=404)

        refresh = RefreshToken.for_user(target)
        logger.info("[IMPERSONATE] %s -> %s (%s)", request.user.email, target.email, role)
        return success_response({
            "access": str(refresh.access_token),
            "refresh": str(refresh),
            "user": {
                "id": target.id,
                "email": target.email,
                "full_name": target.full_name or target.email.split("@")[0],
                "role": target.role,
            },
        }, message=f"Now viewing as {target.email}")
