from gvsdsdk.auth.cookie import ELT_COOKIE_NAME
from gvsdsdk.models import UserRole, Role
from gvsdsdk.model_utils import UUIDObj


class ELTAuthMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        elt_token = request.COOKIES.get(ELT_COOKIE_NAME)
        if elt_token:
            request.elt_token = elt_token
        response = self.get_response(request)
        return response


class CurrentRoleMiddleware:
    """解析 CurrentRoleUUID Cookie，设置 request.current_role 和 request.current_company_uuid

    request.current_role  : gvsdsdk.models.Role 实例（或 None）
    request.current_company_uuid : 通过 UserRole.CompanyUUID 获取当前角色所属公司UUID
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        request.current_role = None
        request.current_company_uuid = None

        # 仅对已认证用户处理角色
        if hasattr(request, 'user') and request.user and request.user.is_authenticated:
            role_uuid_str = request.COOKIES.get('CurrentRoleUUID', '')
            if role_uuid_str:
                try:
                    role_uuid_bytes = UUIDObj(role_uuid_str).bytes
                    # gvsdsdk.UserRole 的 RoleUUID 是 UUIDField，不能用 select_related
                    user_role = UserRole.objects.filter(
                        UserUUID=request.user.UserUUID,
                        RoleUUID=role_uuid_bytes
                    ).first()
                    if user_role:
                        # 单独查询 Role 实例
                        role = Role.objects.filter(RoleUUID=role_uuid_bytes).first()
                        if role:
                            request.current_role = role
                        # 通过 UserRole.CompanyUUID 获取当前公司
                        if user_role.CompanyUUID:
                            request.current_company_uuid = user_role.CompanyUUID
                except Exception:
                    pass

        return self.get_response(request)
