"""后台按俱乐部校验用户/订单是否在当前数据范围内。"""
from rest_framework.response import Response

from jituan.constants import CLUB_ID_DEFAULT, DATA_SCOPE_ALL
from jituan.services.club_context import resolve_club_id_from_request, resolve_club_scope


def user_belongs_to_request(user, request):
    if resolve_club_scope(request) == DATA_SCOPE_ALL:
        return True
    club_id = resolve_club_id_from_request(request)
    user_club = getattr(user, 'ClubID', None) or ''
    return user_club == club_id


def forbid_if_user_out_of_scope(request, user):
    """不属于当前俱乐部时返回 Response，否则返回 None。"""
    if user_belongs_to_request(user, request):
        return None
    return Response({'code': 403, 'msg': '该用户不属于当前俱乐部数据范围'})


def list_response_meta(request):
    return {
        'club_id': resolve_club_id_from_request(request),
        'scope': resolve_club_scope(request),
    }


def order_belongs_to_request(order, request):
    if resolve_club_scope(request) == DATA_SCOPE_ALL:
        return True
    club_id = resolve_club_id_from_request(request)
    order_club = (getattr(order, 'ClubID', None) or '').strip()
    if club_id == CLUB_ID_DEFAULT:
        return order_club in (club_id, '', None) or not order_club
    return order_club == club_id


def forbid_if_order_out_of_scope(request, order):
    if order_belongs_to_request(order, request):
        return None
    return Response({'code': 403, 'msg': '该订单不属于当前俱乐部数据范围'})


def forbid_if_order_mutate_out_of_scope(request, order):
    """
    订单写操作闸门：
    - SINGLE_CLUB：只能处理当前俱乐部订单
    - ALL_CLUBS：仅集团高管可处理（本店超管须切到具体俱乐部）
    """
    if resolve_club_scope(request) == DATA_SCOPE_ALL:
        from jituan.services.group_finance_gate import has_group_finance_exec
        if not has_group_finance_exec(request.user, request):
            return Response({
                'code': 403,
                'msg': '跨俱乐部订单处理仅集团高管可执行，请切换到具体俱乐部后再操作',
            })
        return None
    return forbid_if_order_out_of_scope(request, order)
