from decimal import Decimal

from django.db import models

from .staff_model import Staff


class Place(models.Model):
    name = models.CharField(max_length=150, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'places'
        ordering = ['name']

    def __str__(self):
        return self.name


class Loan(models.Model):

    STATUS_CHOICES = [
        ('active', 'Active'),
        ('completed', 'Completed'),
    ]

    PAYMENT_TYPE_CHOICES = [
        ('daily', 'Daily'),
        ('weekly', 'Weekly'),
        ('monthly', 'Monthly'),
    ]

    # Customer relationship
    customer = models.ForeignKey(
        'NexusApp.Customer',
        on_delete=models.PROTECT,
        related_name='loans'
    )

    # Loan place and staff
    place = models.ForeignKey(
        Place,
        on_delete=models.PROTECT,
        related_name='loans'
    )

    staff = models.ForeignKey(
        Staff,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='loans'
    )

    # Loan details
    loan_date = models.DateField()
    loan_amount = models.DecimalField(
        max_digits=12,
        decimal_places=2
    )

    payment_type = models.CharField(
        max_length=20,
        choices=PAYMENT_TYPE_CHOICES
    )

    first_due_date = models.DateField()
    number_of_dues = models.PositiveIntegerField()

    due_amount = models.DecimalField(
        max_digits=12,
        decimal_places=2
    )

    total_payable = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        default=Decimal('0.00')
    )

    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='active',
        db_index=True
    )

    closed_date = models.DateField(
        null=True,
        blank=True
    )

    notes = models.TextField(
        null=True,
        blank=True
    )

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-id']

    # Customer details now live on the Customer model. These read-only
    # properties keep loan.customer_name / loan.phone_number /
    # loan.aadhaar_number working everywhere (use select_related('customer')
    # in list queries to avoid one extra query per row).
    @property
    def customer_name(self):
        return self.customer.customer_name

    @property
    def phone_number(self):
        return self.customer.phone_number

    @property
    def aadhaar_number(self):
        return self.customer.aadhaar_number

    def save(self, *args, **kwargs):
        self.total_payable = (
            Decimal(str(self.due_amount or 0))
            * int(self.number_of_dues or 0)
        )
        super().save(*args, **kwargs)

    def __str__(self):
        return (
            f"Loan #{self.id} - "
            f"{self.customer.customer_name} "
            f"(₹{self.loan_amount})"
        )


class LoanPayment(models.Model):

    METHOD_CHOICES = [
        ('cash', 'Cash'),
        ('upi', 'UPI'),
    ]

    PAYMENT_STATUS_CHOICES = [
        ('completed', 'Completed'),
        ('pending', 'Pending'),
    ]

    loan = models.ForeignKey(
        Loan,
        on_delete=models.CASCADE,
        related_name='payments'
    )

    payment_date = models.DateField()

    amount = models.DecimalField(
        max_digits=12,
        decimal_places=2
    )

    collected_by = models.ForeignKey(
        Staff,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='collections'
    )

    payment_method = models.CharField(
        max_length=10,
        choices=METHOD_CHOICES,
        default='cash'
    )

    payment_status = models.CharField(
        max_length=10,
        choices=PAYMENT_STATUS_CHOICES,
        default='completed'
    )

    notes = models.CharField(
        max_length=255,
        null=True,
        blank=True
    )

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'loan_payments'
        ordering = ['-payment_date', '-id']
        indexes = [
            models.Index(fields=['loan', 'payment_date'])
        ]

    def __str__(self):
        return f"Payment ₹{self.amount} for loan #{self.loan_id}"