from django.db import models

from core.apps.eggs.models import group
from core.http.models import AbstractBaseModel
from core.http.models.user import User


class Broken(AbstractBaseModel):
    user_id = models.ForeignKey(
        to=User,
        on_delete=models.CASCADE,
        related_name="broken_eggs",
        null=True,
        blank=True,
    )
    group = models.ForeignKey(
        group.Group, on_delete=models.CASCADE, related_name="brokens"
    )
    comment = models.TextField(verbose_name="Comment")
    quantity = models.IntegerField(verbose_name="Quantity")
    price = models.DecimalField(
        max_digits=30, decimal_places=2, default=0, null=True, blank=True
    )

    def save(self, *args, **kwargs):
        is_new = self.pk is None
        if is_new:
            if self.group.quantity < self.quantity:
                raise ValueError(
                    "Quantity cannot be greater than group quantity"
                )
            self.group.quantity -= self.quantity
            self.group.party_id.remaining_count -= self.quantity
            self.group.broken_eggs += self.quantity
            self.group.party_id.profit -= (
                self.group.entry_price * self.quantity
            )
            self.group.party_id.broken_eggs += self.quantity
            self.price = self.group.entry_price * self.quantity
            self.group.save()
            self.group.party_id.save()
        super().save(*args, **kwargs)

    def __str__(self):
        return self.comment

    class Meta:
        verbose_name = "Broken"
        verbose_name_plural = "Brokens"
        db_table = "broken"
