from django.db import models
from django.conf import settings
from accounts.models import VendorProfile
from products.models import Product
from django.db.models import Sum


class Customer(models.Model):
    """CRM Customer model for vendor's customer tracking"""
    vendor = models.ForeignKey(
        VendorProfile,
        on_delete=models.CASCADE,
        related_name='customers'
    )
    name = models.CharField(max_length=200)
    phone = models.CharField(max_length=20)
    email = models.EmailField(blank=True, null=True)
    notes = models.TextField(blank=True, null=True)
    total_purchases = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    purchase_count = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'pos_customers'
        ordering = ['-created_at']
        unique_together = ('vendor', 'phone')

    def __str__(self):
        return f"{self.name} - {self.phone}"

    def update_stats(self):
        """Update customer purchase statistics"""
        sales = self.sales.filter(status='completed')
        self.total_purchases = sales.aggregate(total=Sum('total_price'))['total'] or 0
        self.purchase_count = sales.count()
        self.save()


class Sale(models.Model):
    """POS Sale model for tracking vendor sales"""
    PAYMENT_METHOD_CHOICES = (
        ('cash', 'Cash'),
        ('mpesa', 'M-Pesa'),
        ('bank', 'Bank Transfer'),
        ('credit', 'Credit'),
        ('other', 'Other'),
    )

    STATUS_CHOICES = (
        ('pending', 'Pending'),
        ('completed', 'Completed'),
        ('cancelled', 'Cancelled'),
        ('refunded', 'Refunded'),
    )

    vendor = models.ForeignKey(
        VendorProfile,
        on_delete=models.CASCADE,
        related_name='pos_sales'
    )
    customer = models.ForeignKey(
        Customer,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='sales'
    )
    product = models.ForeignKey(
        Product,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='pos_sales'
    )

    # Sale details
    product_name = models.CharField(max_length=200, help_text="Manual entry if no product link")
    quantity = models.IntegerField(default=1)
    unit_price = models.DecimalField(max_digits=10, decimal_places=2)
    total_price = models.DecimalField(max_digits=12, decimal_places=2)

    # Payment info
    payment_method = models.CharField(max_length=20, choices=PAYMENT_METHOD_CHOICES, default='cash')
    payment_reference = models.CharField(max_length=100, blank=True, null=True)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='completed')

    notes = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'pos_sales'
        ordering = ['-created_at']

    def __str__(self):
        return f"Sale #{self.id} - {self.product_name} ({self.total_price})"

    def save(self, *args, **kwargs):
        # Auto-calculate total if not set
        if not self.total_price:
            self.total_price = self.quantity * self.unit_price

        # Auto-fill product name from product if linked
        if self.product and not self.product_name:
            self.product_name = self.product.name

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

        # Update customer stats after save
        if self.customer:
            self.customer.update_stats()
