from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework.exceptions import APIException

from apps.permissions.models import UserCompanyRole
from  apps.core.services import validate_user_context


class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):

    def validate(self, attrs):
        data = super().validate(attrs)

        user = self.user

        if user.user_type == 'super_admin':
            return data

        two_factor = getattr(user, "two_factor", None)

        if two_factor and two_factor.is_enabled:
            return {
                "two_factor_required": True,
                "user_id": user.id,
            }

        validate_user_context(user)
        #
        # has_role = UserCompanyRole.objects.filter(
        #     user=user,
        #     role__isnull=False
        # ).exists()
        #
        # if not has_role:
        #     raise APIException(
        #         detail="Please ask your dealership admin to assign a role."
        # #    )
        #
        # active_companies = user.companies.filter(is_active=True)
        #
        # if not active_companies.exists():
        #     raise APIException(
        #         detail="No active companies found for this user. "
        #                "Please contact dealership admin."
        # #    )
        #
        # if not user.active_company or not user.active_company.is_active:
        #     first_active_company = active_companies.first()
        #     user.active_company = first_active_company
        #     user.save(update_fields=["active_company"])

        return data
