"""
Party model
"""

from django.db import models
from django.db.models import Sum

from core.http.models import base
from core.http.models.user import User


class Party(base.AbstractBaseModel):
    user_id = models.ForeignKey(
        to=User, on_delete=models.CASCADE, related_name="parties"
    )
    # umumiy soni
    count = models.IntegerField(default=0, null=True, blank=True)
    # sotilgan soni
    sold_count = models.IntegerField(default=0, null=True, blank=True)
    # qolgan soni
    remaining_count = models.IntegerField(default=0, null=True, blank=True)
    # tushum
    benefit = models.DecimalField(
        max_digits=30, decimal_places=2, default=0, null=True, blank=True
    )
    # foyda
    profit = models.DecimalField(
        max_digits=30, decimal_places=2, default=0, null=True, blank=True
    )
    # partiya narxi
    cost = models.DecimalField(
        max_digits=30, decimal_places=2, default=0, null=True, blank=True
    )
    # umumiy narxi
    total_cost = models.DecimalField(
        max_digits=30, decimal_places=2, default=0, null=True, blank=True
    )
    broken_eggs = models.IntegerField(default=0, null=True, blank=True)
    courier_eggs = models.IntegerField(default=0, null=True, blank=True)

    @staticmethod
    def get_total_benefit():
        return Party.objects.aggregate(
            total_count=Sum("count"),  # umumiy mahsulot soni
            total_sold_count=Sum(
                "sold_count"
            ),  # umumiy sotilgan mahsulot soni
            total_remaining_count=Sum(
                "remaining_count"
            ),  # umumiy qolgan mahsulot soni
            total_broken_eggs=Sum("broken_eggs"),  # umumiy singan soni
            total_courier_eggs=Sum(
                "courier_eggs"
            ),  # umumiy kuryerlar tomonidan olingan soni
        )

    def clean(self):
        if self.count < 0:
            raise ValueError("Count can't be negative")
        if self.sold_count < 0:
            raise ValueError("Sold count can't be negative")
        if self.remaining_count < 0:
            raise ValueError("Remaining count can't be negative")
        if self.benefit < 0:
            raise ValueError("Benefit can't be negative")
        if self.cost < 0:
            raise ValueError("Cost can't be negative")
        if self.total_cost < 0:
            raise ValueError("Total cost can't be negative")

    def update_total_cost(self):
        total_invoice_price = (
            self.invoices.aggregate(Sum("price"))["price__sum"] or 0
        )
        self.total_cost = self.cost + total_invoice_price
        self.profit -= total_invoice_price
        self.save()

    def __str__(self):
        return f"User - {self.user_id}, price - {self.benefit}"

    class Meta:
        verbose_name = "Party"
        verbose_name_plural = "Parties"
        db_table = "party"
