from django.db import models
from shop_management.models.base import DataRoot
from shop_management.models.data.purchase import Purchase
from shop_management.models.data.shop_account import Account
from shop_management.models.data.utils import Currency
from django.utils import timezone

class PurchasePayment(DataRoot):
    purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE, related_name='payments')
    account = models.ForeignKey(
        Account,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="purchase_payments",
    )
    currency = models.ForeignKey(
        Currency, 
        on_delete=models.SET_NULL, 
        null=True, 
        blank=True, 
        related_name='payments'
    )
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    exchange_rate = models.DecimalField(max_digits=20, decimal_places=6, default=1)
    converted_amount = models.DecimalField(max_digits=18, decimal_places=2, default=0)
    payment_date = models.DateTimeField(default=timezone.now)
    notes = models.TextField(blank=True, null=True)

    def __str__(self):
        curr = self.currency.title if self.currency else "Unknown Currency"
        return f"Payment of {self.amount} {curr} for Purchase ID {self.purchase.id}"

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        # After saving the payment, update the status of the purchase.
        self.purchase.update_status()
