from django.db import models
from django.conf import settings
from credit_scoring.models import CreditApplication
from documents.models import Document
from decimal import Decimal
import uuid

class PurchaseOrder(models.Model):
    STATUS_CHOICES = [
        ('DRAFT', 'Draft'),
        ('SUBMITTED', 'Submitted'),
        ('VERIFIED', 'PO Verified'),
        ('SUPPLIER_ORDERED', 'Supplies Ordered'),
        ('GOODS_RECEIVED', 'Goods Received'),
        ('INVOICE_SUBMITTED', 'Invoice Submitted'),
        ('FULLY_FUNDED', 'Fully Funded'),
        ('REPAID', 'Repaid'),
        ('DECLINED', 'Declined'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    credit_application = models.ForeignKey(CreditApplication, on_delete=models.CASCADE, related_name='purchase_orders')
    po_number = models.CharField(max_length=100, unique=True)
    supplier_name = models.CharField(max_length=200)
    supplier_contact = models.CharField(max_length=200)
    order_date = models.DateField()
    delivery_date = models.DateField()
    total_amount = models.DecimalField(max_digits=15, decimal_places=2)
    funded_amount = models.DecimalField(max_digits=15, decimal_places=2, default=0)
    remaining_amount = models.DecimalField(max_digits=15, decimal_places=2, default=0)
    interest_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal('5.68'))
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='DRAFT')
    po_document = models.ForeignKey(Document, on_delete=models.SET_NULL, null=True, blank=True, related_name='po_documents')
    invoice_document = models.ForeignKey(Document, on_delete=models.SET_NULL, null=True, blank=True, related_name='po_invoices')
    notes = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'purchase_orders'
        ordering = ['-order_date']
    
    def save(self, *args, **kwargs):
        self.remaining_amount = self.total_amount - self.funded_amount
        super().save(*args, **kwargs)
    
    def __str__(self):
        return f"PO {self.po_number} - {self.supplier_name} - {self.status}"
    
    def calculate_funding(self):
        """Calculate funding amount (typically 80-90% of PO value)"""
        funding_percentage = Decimal('0.85')  # 85% advance
        return self.total_amount * funding_percentage

class FundingDisbursement(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    purchase_order = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE, related_name='disbursements')
    amount = models.DecimalField(max_digits=15, decimal_places=2)
    disbursement_date = models.DateField(auto_now_add=True)
    transaction_reference = models.CharField(max_length=100, unique=True)
    paid_to_supplier = models.BooleanField(default=False)
    supplier_payment_reference = models.CharField(max_length=100, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'funding_disbursements'
    
    def __str__(self):
        return f"Disbursement for {self.purchase_order.po_number} - {self.amount}"