from typing import Any

from django.contrib.auth.models import update_last_login
from rest_framework_simplejwt import serializers as auth_serializers
from rest_framework_simplejwt.settings import api_settings
from rest_framework_simplejwt.tokens import RefreshToken


class TokenObtainPairSerializer(auth_serializers.TokenObtainSerializer):
    token_class = RefreshToken

    def validate(self, attrs: dict[str, Any]) -> dict[str, str]:
        data = super().validate(attrs)

        refresh = self.get_token(self.user)

        data["refresh_token"] = str(refresh)
        data["access_token"] = str(refresh.access_token)
        data["expires_in"] = int(refresh.access_token.lifetime.total_seconds())

        if api_settings.UPDATE_LAST_LOGIN:
            update_last_login(None, self.user)

        return data
