from decimal import Decimal

from apps.agreement.models import Agreement
from django.db import models
from django.utils.translation import gettext_lazy as _


class Rant(models.Model):
    FLOOR_CHOICES = (
        (0, "UnderGround"),
        (1, "First floor"),
        (2, "Second Floor"),
        (3, "Third Floor"),
        (4, "Fourth Floor"),
        (5, "Fifth Floor"),
    )

    MONTH_CHOICES = (
        (1, "حمل"),
        (2, "ثور"),
        (3, "جوزا"),
        (4, "سرطان"),
        (5, "اسد"),
        (6, "سنبله"),
        (7, "میزان"),
        (8, "عقرب"),
        (9, "قوس"),
        (10, "جدی"),
        (11, "دلو"),
        (12, "حوت"),
    )

    year = models.CharField(max_length=255)
    floor = models.CharField(_("Floor"), choices=FLOOR_CHOICES, max_length=50)
    time = models.CharField(_("Time"), choices=MONTH_CHOICES, max_length=250)
    total = models.DecimalField(
        _("Total"), max_digits=10, decimal_places=2, default=Decimal("0.00")
    )
    customers_list = models.JSONField(default=dict)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = _("Rant")
        verbose_name_plural = _("Rants")

    def get_customers_list(self):
        agreements = Agreement.objects.filter(status="Active", floor=self.floor)

        customers_data = {}
        total_rent = Decimal("0.00")

        for agreement in agreements:
            # Default 'taken' and 'remainder' to 0.0, and ensure 'rant' is always present
            taken = Decimal("0.00")
            remainder = Decimal("0.00")

            customer_data = {
                "rant": (
                    float(agreement.rant) if agreement.rant is not None else 0.0
                ),  # Ensure 'rant' is always a float
                "taken": float(taken),  # Taken is always 0
                "remainder": float(remainder),  # Remainder is always 0
            }
            customers_data[agreement.customer.id] = customer_data
            total_rent += agreement.rant

        return customers_data, total_rent

    def save(self, *args, **kwargs):
        if not self.pk:
            customers_data, total_rent = self.get_customers_list()
            self.customers_list = customers_data
            self.total = total_rent

        super().save(*args, **kwargs)
