from decimal import Decimal

from core.apps.eggs.models.debt import Debt, DebtTypeEnum
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from core.apps.eggs.models import History, Monitoring, Notification
from core.apps.eggs.models.market import Market
from core.http.models import User
from core.apps.eggs.tasks.send_sms import send_sms_msg


class AddDebtView(APIView):
    @swagger_auto_schema(
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                "market_id": openapi.Schema(
                    type=openapi.TYPE_INTEGER,
                    description="Market ID",
                ),
                "price": openapi.Schema(
                    type=openapi.TYPE_NUMBER,
                    description="Price",
                ),
            },
        ),
        responses={
            200: openapi.Schema(
                type=openapi.TYPE_OBJECT,
                properties={
                    "message": openapi.Schema(
                        type=openapi.TYPE_STRING,
                        description="Debt added successfully.",
                    ),
                },
            ),
            400: openapi.Schema(
                type=openapi.TYPE_OBJECT,
                properties={
                    "error": openapi.Schema(
                        type=openapi.TYPE_STRING,
                        description="Detailed error message when the request fails with a 400 status code.",
                    ),
                },
            ),
            404: openapi.Schema(
                type=openapi.TYPE_OBJECT,
                properties={
                    "error": openapi.Schema(
                        type=openapi.TYPE_STRING,
                        description="Detailed error message when the request fails with a 404 status code.",
                    ),
                },
            ),
        },
    )
    def post(self, request, *args, **kwargs):
        market_id = request.data.get("market_id")
        raw_price = request.data.get("price")

        if not all([market_id, raw_price]):
            return Response(
                {"error": "Both market_id and price are required."},
                status=status.HTTP_400_BAD_REQUEST,
            )

        try:
            price = Decimal(str(raw_price))
        except Exception:
            return Response(
                {"error": "Invalid price value."},
                status=status.HTTP_400_BAD_REQUEST,
            )

        try:
            market = Market.objects.get(pk=market_id)
        except Market.DoesNotExist:
            return Response(
                {"error": "Market with given id does not exist."},
                status=status.HTTP_404_NOT_FOUND,
            )

        Debt.objects.create(
            market=market, debt_price=price, debt_type=DebtTypeEnum.ADDED.value
        )

        History.objects.create(
            content_object=market,
            action="add_debt_created",
            user_id=request.user,
            comment=f"Qarz qo'shildi: {price}",
            avatar=market.avatar,
            reason=f"Qarz qo'shildi: {price}",
            created_by=market.name,
            created_who=f"{request.user.first_name} {request.user.last_name}",
        )
        notification_users = User.objects.filter(role="admin")
        for user in notification_users:
            Notification.objects.create(
                user=user,
                title=f"Qarz muvaffaqiyatli qo'shildi {price} so'm",
                body=f"Qarz muvaffaqiyatli qo'shildi {market.name} ga {price} so'm",
            )

        message = f"Hurmatli {market.user_id.first_name} {market.user_id.last_name}, Sizning  Gold-eggs.uz tuxum yetkazib berish xizmati ilovasidagi xaridingizga {price} so'm qarz qo'shib qo'yildi Umumiy balans: {market.debt_unpaid} so'm Batafsil: +998914249515"

        try:
            send_sms_msg.delay(market.user_id.phone, message)
        except Exception:
            pass

        return Response(
            {
                "message": "Qarz muvaffaqiyatli qo'shildi.",
                "debt_unpaid": f"{market.debt_unpaid}",
                "market_name": f"{market.name}",
                "market_phone": f"{market.phone}",
                "market_company": f"{market.company_name}",
            },
            status=status.HTTP_200_OK,
        )
