from django.db import models
from rest_framework.exceptions import ValidationError

from core.http.models import AbstractBaseModel


class DebtTypeEnum(models.TextChoices):
    ADDED = "added"
    LOST = "lost"


class Debt(AbstractBaseModel):
    market = models.ForeignKey(
        to="Market", on_delete=models.CASCADE, related_name="debts"
    )
    debt_price = models.DecimalField(max_digits=30, decimal_places=2)
    debt_type = models.CharField(
        max_length=255,
        choices=DebtTypeEnum.choices,
        default=DebtTypeEnum.LOST.value,
    )

    def save(self, *args, **kwargs):
        if self.pk is None:
            if self.debt_type == DebtTypeEnum.ADDED.value:
                # self.market.debt_paid -= self.debt_price
                self.market.debt_unpaid += self.debt_price
            elif self.debt_type == DebtTypeEnum.LOST.value:
                if self.debt_price > self.market.debt_unpaid:
                    raise ValueError(
                        "Debt price cannot be greater than unpaid debt."
                    )
                self.market.debt_paid += self.debt_price
                self.market.debt_unpaid -= self.debt_price
            else:
                raise ValidationError(
                    detail={"debt_type": "invlaid debt_type"}
                )
            self.market.save()
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.debt_price} - {self.market.name}"


# from django.db import models
# from django.core.exceptions import ValidationError
#
#
# class Debt(AbstractBaseModel):
#     market = models.ForeignKey(to="Market", on_delete=models.CASCADE)
#     order = models.ForeignKey(to="Order", on_delete=models.CASCADE)
#     debt_price = models.DecimalField(max_digits=30, decimal_places=2)
#
#     def save(self, *args, **kwargs):
#         if self.pk is None:
#             if self.debt_price > self.market.debt_unpaid:
#                 raise ValidationError("Debt price cannot be greater than unpaid debt.")
#
#             self.market.debt_paid += self.debt_price
#             self.market.debt_unpaid -= self.debt_price
#             self.market.save()
#
#             self.order.price_paid += self.debt_price
#             self.order.debt -= self.debt_price
#             self.order.save()
#
#             order_items = OrderItems.objects.filter(order_id=self.order.id)
#             for item in order_items:
#                 party = item.courier_product_id.group_id.party_id
#                 if party:
#                     party.benefit += self.debt_price
#                     party.save()
#
#         super().save(*args, **kwargs)
#
#     def __str__(self):
#         return f"{self.debt_price} - {self.market.name} - {self.order.id}"
