from django.db import models
from shop_management.models.base import DataRoot
from shop_management.models.data.utils import Currency
from shop_management.models.data.sale import Sale
from django.utils import timezone

class SalePayment(DataRoot):
    sale = models.ForeignKey(Sale, on_delete=models.CASCADE, related_name='payments')
    currency = models.ForeignKey(
        Currency, 
        on_delete=models.SET_NULL, 
        null=True, 
        blank=True, 
        related_name='sale_payments'
    )
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    payment_date = models.DateTimeField(default=timezone.now)
    notes = models.TextField(blank=True, null=True)
    # Optionally add fields like payment_method, transaction_id, etc.

    def __str__(self):
        curr = self.currency.title if self.currency else "Unknown Currency"
        return f"Payment of {self.amount} {curr} for Sale ID {self.sale.id}"

    def save(self, *args, **kwargs):
        # Save the payment first...
        super().save(*args, **kwargs)
        # ...then update the sale status based on the new payment.
        self.sale.update_status()
