"""
Monthly Chit Fund.

  ChitGroup   one chit (e.g. "Gold 1 Lakh": 20 members x Rs 5,000 x 20 months)
  ChitMember  a person in the chit (ticket number, contact details)
  ChitTerm    one month of the chit. The admin can set, per month, how much each
              member pays (due_amount) and how much the winner can claim
              (prize_amount); the winner + claim status are recorded here.
  ChitPayment money a member paid for a term (several part-payments allowed)
"""
from decimal import Decimal

from django.db import models


class ChitGroup(models.Model):
    AUCTION_CHOICES = [('auction', 'Auction'), ('lottery', 'Lottery / Draw'), ('fixed', 'Fixed order')]
    STATUS_CHOICES = [('active', 'Active'), ('closed', 'Closed')]

    name = models.CharField(max_length=150)
    chit_value = models.DecimalField(max_digits=14, decimal_places=2)          # total pot
    total_members = models.PositiveIntegerField()
    total_months = models.PositiveIntegerField()
    monthly_amount = models.DecimalField(max_digits=12, decimal_places=2)      # default contribution
    start_month = models.DateField(help_text='First month of the chit (day is ignored)')
    due_day = models.PositiveIntegerField(default=5)
    commission_percent = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal('5'))
    auction_type = models.CharField(max_length=10, choices=AUCTION_CHOICES, default='auction')
    place = models.ForeignKey('NexusApp.Place', on_delete=models.SET_NULL, null=True, blank=True,
                              related_name='chits')
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='active', db_index=True)
    notes = models.TextField(blank=True, default='')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'chit_groups'
        ordering = ['-id']

    def __str__(self):
        return self.name


class ChitMember(models.Model):
    chit = models.ForeignKey(ChitGroup, on_delete=models.CASCADE, related_name='members')
    ticket_no = models.PositiveIntegerField()
    name = models.CharField(max_length=150)
    phone = models.CharField(max_length=15)
    address = models.CharField(max_length=255, blank=True, default='')
    aadhaar_number = models.CharField(max_length=12, blank=True, default='')
    nominee = models.CharField(max_length=150, blank=True, default='')
    joined_date = models.DateField(null=True, blank=True)
    notes = models.CharField(max_length=255, blank=True, default='')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'chit_members'
        ordering = ['ticket_no']
        constraints = [
            models.UniqueConstraint(fields=['chit', 'ticket_no'], name='unique_chit_ticket'),
        ]

    def __str__(self):
        return f'#{self.ticket_no} {self.name}'


class ChitTerm(models.Model):
    chit = models.ForeignKey(ChitGroup, on_delete=models.CASCADE, related_name='terms')
    term_no = models.PositiveIntegerField()
    month = models.DateField()                               # first day of the month
    due_date = models.DateField()
    due_amount = models.DecimalField(max_digits=12, decimal_places=2)        # each member pays
    prize_amount = models.DecimalField(max_digits=14, decimal_places=2)      # winner can claim
    bid_discount = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal('0'))
    commission_amount = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal('0'))
    dividend_per_member = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal('0'))
    winner = models.ForeignKey(ChitMember, on_delete=models.SET_NULL, null=True, blank=True,
                               related_name='won_terms')
    claimed = models.BooleanField(default=False)
    claimed_date = models.DateField(null=True, blank=True)
    notes = models.CharField(max_length=255, blank=True, default='')

    class Meta:
        db_table = 'chit_terms'
        ordering = ['chit', 'term_no']
        constraints = [
            models.UniqueConstraint(fields=['chit', 'term_no'], name='unique_chit_term'),
        ]

    def __str__(self):
        return f'{self.chit} - month {self.term_no}'


class ChitPayment(models.Model):
    METHOD_CHOICES = [('cash', 'Cash'), ('upi', 'UPI')]

    term = models.ForeignKey(ChitTerm, on_delete=models.CASCADE, related_name='payments')
    member = models.ForeignKey(ChitMember, on_delete=models.CASCADE, related_name='payments')
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    paid_date = models.DateField()
    method = models.CharField(max_length=10, choices=METHOD_CHOICES, default='cash')
    collected_by = models.ForeignKey('NexusApp.Staff', on_delete=models.SET_NULL, null=True, blank=True,
                                     related_name='chit_collections')
    notes = models.CharField(max_length=255, blank=True, default='')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'chit_payments'
        ordering = ['-paid_date', '-id']
        indexes = [models.Index(fields=['term', 'member'])]

    def __str__(self):
        return f'{self.member} paid {self.amount} for {self.term}'
