from rest_framework.exceptions import APIException
from apps.permissions.repositories import UserCompanyRoleRepository


def validate_user_context(user):
    """
    Ensures user has role and active company.
    Call this ONLY after authentication (password + 2FA).
    """
    repo = UserCompanyRoleRepository()

    if not repo.has_role(user):
        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:
        user.active_company = active_companies.first()
        user.save(update_fields=["active_company"])
