from django.db import models
from decimal import Decimal
from django.core.exceptions import ValidationError

from django.db import models
from django.core.exceptions import ValidationError
from decimal import Decimal


class Customer(models.Model):
    customer_id = models.CharField(max_length=10, unique=True, editable=False)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100, blank=True)
    phone = models.CharField(max_length=15, unique=True)
    email = models.EmailField(blank=True)
    address = models.TextField(blank=True)
    date_added = models.DateTimeField(auto_now_add=True)

    # Fields to handle credit
    credit_limit = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal("0.00"))
    credit_balance = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal("0.00"))  # Amount owed by the customer

    def save(self, *args, **kwargs):
        if not self.customer_id:
            last_customer = Customer.objects.order_by('-id').first()
            new_id = (int(last_customer.customer_id[3:]) + 1) if last_customer else 1
            self.customer_id = f'CST{new_id:04d}'

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

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

    def can_purchase_on_credit(self, amount):
        """
        Check if a customer can make a purchase on credit without exceeding their credit limit.
        """
        return (self.credit_balance + amount) <= self.credit_limit

    def update_credit_balance(self, amount, is_payment=False):
        """
        Updates the credit balance based on a credit purchase or a payment.

        - `amount`: Decimal value of transaction.
        - `is_payment`: Boolean. If `True`, it means the customer is making a payment, so we decrease the balance.
        """
        if is_payment:
            new_balance = self.credit_balance - amount  # Reduce balance when paying
            if new_balance < Decimal("0.00"):
                raise ValidationError("Credit balance cannot be negative after payment.")
        else:
            new_balance = self.credit_balance + amount  # Increase balance for purchases
            if new_balance > self.credit_limit:
                raise ValidationError("Customer cannot exceed credit limit.")

        self.credit_balance = new_balance
        self.save()
