from datetime import datetime
from datetime import timedelta

from django.db.models import Sum
from rest_framework import serializers
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from core.apps.eggs.models import Monitoring


class MonitoringSerializer(serializers.ModelSerializer):
    class Meta:
        model = Monitoring
        fields = [
            "id",
            "content_type",
            "object_id",
            "action",
            "timestamp",
            "created_by",
            "created_who",
            "reason",
            "comment",
            "price",
        ]


class MonitoringSummarySerializer(serializers.Serializer):
    from_date = serializers.CharField()
    end_date = serializers.CharField()
    enter_price = serializers.DecimalField(max_digits=30, decimal_places=2)
    exit_price = serializers.DecimalField(max_digits=30, decimal_places=2)
    profit = serializers.DecimalField(max_digits=30, decimal_places=2)
    results = MonitoringSerializer(many=True)


class MonitoringSummaryView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, *args, **kwargs):
        from_date = request.query_params.get("from_date")
        end_date = request.query_params.get("end_date")

        if from_date and end_date:
            start_date = datetime.strptime(from_date, "%Y-%m-%d")
            end_date = datetime.strptime(end_date, "%Y-%m-%d") + timedelta(
                days=1
            )
        else:
            start_date = None
            end_date = None

        enter_actions = ["Kirim", "debt_created", "order_created"]
        exit_actions = [
            "Chiqim",
            "additional_cost_created",
            "broken_created",
            "party_created",
        ]

        if start_date and end_date:
            enter_price = (
                Monitoring.objects.filter(
                    action__in=enter_actions,
                    timestamp__range=[start_date, end_date],
                ).aggregate(total=Sum("price"))["total"]
                or 0
            )

            exit_price = (
                Monitoring.objects.filter(
                    action__in=exit_actions,
                    timestamp__range=[start_date, end_date],
                ).aggregate(total=Sum("price"))["total"]
                or 0
            )

            results = Monitoring.objects.filter(
                timestamp__range=[start_date, end_date]
            )
        else:
            enter_price = (
                Monitoring.objects.filter(action__in=enter_actions).aggregate(
                    total=Sum("price")
                )["total"]
                or 0
            )

            exit_price = (
                Monitoring.objects.filter(action__in=exit_actions).aggregate(
                    total=Sum("price")
                )["total"]
                or 0
            )

            results = Monitoring.objects.all()

        profit = enter_price - exit_price

        data = {
            "from_date": from_date,
            "end_date": end_date,
            "enter_price": enter_price,
            "exit_price": exit_price,
            "profit": profit,
            "results": results,
        }

        serializer = MonitoringSummarySerializer(data)
        return Response(serializer.data)
