"""客服后台：角色协议配置。"""
from rest_framework.parsers import FormParser, JSONParser, MultiPartParser
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 import role_agreement as svc
from jituan.services.club_context import resolve_club_id_from_request

PERM_CODE = 'xycfg001'


def _auth(request, perm_code: str = PERM_CODE):
    username = (request.data.get('username') or request.data.get('phone') or '').strip()
    if not username:
        return None, None, Response({'code': 400, 'msg': '缺少username'})
    kefu, permissions = verify_kefu_permission(request, username)
    if kefu is None:
        return None, None, permissions
    codes = set(permissions or [])
    user = getattr(request, 'user', None)
    if getattr(user, 'IsSuperuser', False) or '000001' in codes:
        return kefu, permissions, None
    if perm_code not in codes:
        return None, None, Response({'code': 403, 'msg': f'无权限（需要 {perm_code}）'})
    return kefu, permissions, None


class RoleAgreementAdminView(APIView):
    """
    POST /jituan/houtai/role-agreement
    action: get | save | publish | upload
    """
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser, MultiPartParser, FormParser]

    def post(self, request):
        kefu, permissions, err = _auth(request)
        if err:
            return err
        action = (request.data.get('action') or 'get').strip().lower()
        operator = getattr(getattr(request, 'user', None), 'UserUID', '') or ''

        if action == 'get':
            return Response({'code': 0, 'msg': 'ok', 'data': svc.build_admin_payload(request)})

        if action == 'save':
            data, msg = svc.save_agreement(request, request.data, operator=operator)
            if msg:
                return Response({'code': 400, 'msg': msg})
            return Response({'code': 0, 'msg': '已保存', 'data': data})

        if action == 'publish':
            data, msg = svc.publish_agreement(request, request.data, operator=operator)
            if msg:
                return Response({'code': 400, 'msg': msg})
            return Response({'code': 0, 'msg': '已发布新版本', 'data': data})

        if action == 'upload':
            f = request.FILES.get('file')
            if not f:
                return Response({'code': 400, 'msg': '缺少 file'})
            club_id = resolve_club_id_from_request(request) or ''
            path, msg = svc.upload_agreement_image(f, club_id, kind='content')
            if msg:
                return Response({'code': 400, 'msg': msg})
            return Response({'code': 0, 'msg': '上传成功', 'data': {'url': path, 'path': path}})

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