from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response


class UpsertMixin:
    upsert_lookup_field = None

    @action(detail=False, methods=['post'])
    def upsert(self, request):
        if not self.upsert_lookup_field:
            raise AssertionError(
                f"{self.__class__.__name__} must define `upsert_lookup_field`"
            )
        lookup_value = request.data.get(self.upsert_lookup_field)

        instance = self.queryset.model.objects.filter(
            **{self.upsert_lookup_field: lookup_value}
        ).first()

        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)

        obj = serializer.save()

        return Response(
            self.get_serializer(obj).data,
            status=status.HTTP_201_CREATED if instance is None else status.HTTP_200_OK
        )
