# ============================================================
# ADDITIVE: Token refresh for Company / Employee / SuperAdmin
#
# WHY A CUSTOM VIEW (and not simplejwt's stock TokenRefreshView):
# newer simplejwt versions look up a Django auth User from the
# `user_id` claim. Our tokens carry company_id / employee_code /
# superadmin profile id there, so the stock view would 500/401.
#
# POST /api/auth/token/refresh/        (also mounted at
#      /company/auth/refresh/ and /employee/auth/refresh/)
# body: {"refresh": "<refresh token>"}
# -> {"status":"success","code":"token_refreshed",
#     "data":{"access":"<new access token>"}}
#
# All custom claims (type, user_id, company_id, role ...) are
# carried over into the new access token automatically.
# The account is re-checked (still exists / active) before a
# new access token is issued.
# ============================================================
from rest_framework import status as http_status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.exceptions import AuthenticationFailed, TokenError
from rest_framework_simplejwt.tokens import RefreshToken


def _err(code, message, status):
    return Response({
        "status": "error",
        "code": code,
        "message": message,
        "data": None,
    }, status=status)


class AuthTokenRefreshView(APIView):
    authentication_classes = []
    permission_classes = []

    # set on subclasses to restrict which token type may be refreshed here
    allowed_types = ("company", "employee", "superadmin")

    def post(self, request):
        raw = request.data.get("refresh")
        if not raw:
            return _err("missing_fields", "refresh token is required.",
                        http_status.HTTP_400_BAD_REQUEST)

        try:
            refresh = RefreshToken(raw)
        except TokenError:
            return _err("refresh_token_invalid",
                        "Refresh token is invalid or expired. Please login again.",
                        http_status.HTTP_401_UNAUTHORIZED)

        token_type = refresh.get("type")
        if token_type not in self.allowed_types:
            return _err("invalid_token_type", "Invalid refresh token type.",
                        http_status.HTTP_401_UNAUTHORIZED)

        access = refresh.access_token

        # Re-check that the account behind the token is still usable.
        try:
            if token_type == "company":
                from .company_authentication import CompanyJWTAuthentication
                CompanyJWTAuthentication().get_user(access)
            elif token_type == "employee":
                from Employee.employee_authentication import EmployeeJWTAuthentication
                EmployeeJWTAuthentication().get_user(access)
            elif token_type == "superadmin":
                # ADDITIVE: a deactivated SuperAdmin / platform staff must not get new tokens
                from SuperAdmin.models import SuperAdminProfile
                profile = SuperAdminProfile.objects.select_related("user").filter(pk=refresh.get("user_id")).first()
                if profile is None or not profile.is_active or not profile.user.is_active:
                    return _err("superadmin_disabled", "SuperAdmin account is inactive.",
                                http_status.HTTP_401_UNAUTHORIZED)
        except AuthenticationFailed as exc:
            detail = exc.detail if isinstance(exc.detail, dict) else {}
            return _err(detail.get("code", "account_not_valid"),
                        detail.get("message", "Account is not valid. Please login again."),
                        http_status.HTTP_401_UNAUTHORIZED)

        return Response({
            "status": "success",
            "code": "token_refreshed",
            "message": "Access token refreshed.",
            "data": {"access": str(access)},
        }, status=http_status.HTTP_200_OK)


class CompanyTokenRefreshView(AuthTokenRefreshView):
    allowed_types = ("company",)


class EmployeeTokenRefreshView(AuthTokenRefreshView):
    allowed_types = ("employee",)
    