from django.db import transaction
from django.db.models import F
from rest_framework import permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView

from api_v1.serializers import PrintCountDeltaSerializer
from api_v1.enums import PrintCountObjectType
from printing import models as printing_models


class PrintCountDeltaView(APIView):
    """通用打印次数递增接口"""

    permission_classes = [permissions.IsAuthenticated]

    OBJECT_MODEL_MAP = {
        PrintCountObjectType.PRINTING_ORDER: printing_models.PrintingOrder,
        PrintCountObjectType.PLATE_ORDER: printing_models.PlateOrder,
    }

    def post(self, request, *args, **kwargs):
        serializer = PrintCountDeltaSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data

        model = self.OBJECT_MODEL_MAP.get(data['object_type'])
        if model is None:
            return Response(
                {'detail': '不支持的对象类型'},
                status=status.HTTP_400_BAD_REQUEST,
            )

        with transaction.atomic():
            updated = model.objects.filter(id=data['object_id']).update(
                print_count=F('print_count') + data['delta']
            )
            if not updated:
                return Response(
                    {'detail': '指定对象不存在'},
                    status=status.HTTP_404_NOT_FOUND,
                )
            fresh_value = model.objects.only('print_count').get(id=data['object_id']).print_count

        return Response(
            {
                'object_type': data['object_type'],
                'object_id': data['object_id'],
                'delta': data['delta'],
                'print_count': fresh_value,
            },
            status=status.HTTP_200_OK,
        )


adjust_print_count = PrintCountDeltaView.as_view()

