from django.db import models
from django.conf import settings
from invoice_discounting.models import Invoice, InvoicePayment
from purchase_order.models import PurchaseOrder, FundingDisbursement
import uuid

class PaymentTransaction(models.Model):
    PAYMENT_METHODS = [
        ('CARD', 'Credit/Debit Card'),
        ('EFT', 'Electronic Transfer'),
        ('PAYPAL', 'PayPal'),
        ('MOMO', 'Mobile Money'),
        ('CASH', 'Cash'),
    ]
    
    STATUS_CHOICES = [
        ('PENDING', 'Pending'),
        ('PROCESSING', 'Processing'),
        ('COMPLETED', 'Completed'),
        ('FAILED', 'Failed'),
        ('REFUNDED', 'Refunded'),
        ('CANCELLED', 'Cancelled'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    transaction_id = models.CharField(max_length=100, unique=True)
    invoice = models.ForeignKey(Invoice, on_delete=models.SET_NULL, null=True, blank=True, related_name='payment_transactions')
    purchase_order = models.ForeignKey(PurchaseOrder, on_delete=models.SET_NULL, null=True, blank=True, related_name='payment_transactions')
    amount = models.DecimalField(max_digits=15, decimal_places=2)
    payment_method = models.CharField(max_length=20, choices=PAYMENT_METHODS)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='PENDING')
    stripe_payment_intent_id = models.CharField(max_length=100, blank=True)
    paypal_order_id = models.CharField(max_length=100, blank=True)
    customer_name = models.CharField(max_length=200)
    customer_email = models.EmailField()
    payment_date = models.DateTimeField(null=True, blank=True)
    metadata = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'payment_transactions'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"Transaction {self.transaction_id} - {self.amount} - {self.status}"

class PaymentGatewayConfig(models.Model):
    GATEWAY_CHOICES = [
        ('STRIPE', 'Stripe'),
        ('PAYPAL', 'PayPal'),
        ('YOUR_CODING', 'YourCoding Payment Gateway'),
    ]
    
    gateway_name = models.CharField(max_length=50, choices=GATEWAY_CHOICES, unique=True)
    is_active = models.BooleanField(default=True)
    api_key = models.CharField(max_length=255)
    api_secret = models.CharField(max_length=255)
    webhook_secret = models.CharField(max_length=255, blank=True)
    environment = models.CharField(max_length=20, choices=[('TEST', 'Test/Sandbox'), ('LIVE', 'Live Production')], default='TEST')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'payment_gateway_configs'
    
    def __str__(self):
        return f"{self.gateway_name} ({self.environment})"