"""集团后台：俱乐部订单单向互通抢单配置。"""
from rest_framework.parsers import JSONParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from backend.utils import verify_kefu_permission
from jituan.services.admin_context import can_manage_admin_assignments
from jituan.services.order_grab_share import add_grab_link, delete_grab_link, list_grab_links


class ClubOrderGrabLinkManageView(APIView):
    """
    POST /jituan/houtai/order-grab-link
    action: list | add | delete
    仅集团权限（can_manage_admin_assignments）可操作。
    """
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def post(self, request):
        username = (request.data.get('username') or request.data.get('phone') or '').strip()
        if not username:
            return Response({'code': 400, 'msg': '缺少username'})
        kefu, permissions = verify_kefu_permission(request, username)
        if kefu is None:
            return permissions
        if not can_manage_admin_assignments(request.user, permissions):
            return Response({'code': 403, 'msg': '仅集团权限可配置订单互通'})

        action = (request.data.get('action') or 'list').strip()
        if action == 'list':
            return Response({'code': 0, 'msg': 'ok', 'data': {'list': list_grab_links()}})

        if action == 'add':
            data, err = add_grab_link(
                request.data.get('grabber_club_id'),
                request.data.get('order_club_id'),
            )
            if err:
                return Response({'code': 400, 'msg': err})
            return Response({'code': 0, 'msg': '已添加', 'data': data})

        if action == 'delete':
            ok, err = delete_grab_link(request.data.get('id'))
            if not ok:
                return Response({'code': 400, 'msg': err or '删除失败'})
            return Response({'code': 0, 'msg': '已删除'})

        return Response({'code': 400, 'msg': '无效 action'})
