from django.db import models
from django.core.validators import MinValueValidator
from decimal import Decimal


class TransactionLink(models.Model):
    """
    Bridge between dj-stripe (public schema) and tenant Events.
    
   Links Stripe PaymentIntents to schedule Events in the tenant schema.
    Since dj-stripe models live in the public schema, we need this bridge
    to maintain tenant isolation.
    """
    
    class Status(models.TextChoices):
        PENDING = 'PENDING', 'Pending'
        PROCESSING = 'PROCESSING', 'Processing'
        SUCCEEDED = 'SUCCEEDED', 'Succeeded'
        FAILED = 'FAILED', 'Failed'
        REFUNDED = 'REFUNDED', 'Refunded'
        CANCELED = 'CANCELED', 'Canceled'
    
    # Link to tenant event
    event = models.ForeignKey(
        'schedule.Event',
        on_delete=models.CASCADE,
        related_name='transactions'
    )
    
    # Stripe identifiers
    payment_intent_id = models.CharField(
        max_length=255,
        unique=True,
        db_index=True,
        help_text="Stripe PaymentIntent ID"
    )
    
    # Financial fields
    amount = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        validators=[MinValueValidator(Decimal('0.01'))],
        help_text="Total amount in tenant currency"
    )
    
    application_fee_amount = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        validators=[MinValueValidator(Decimal('0.00'))],
        help_text="Platform fee amount (e.g., 5% of total)"
    )
    
    currency = models.CharField(
        max_length=3,
        default='USD',
        help_text="ISO 4217 currency code"
    )
    
    # Status tracking
    status = models.CharField(
        max_length=20,
        choices=Status.choices,
        default=Status.PENDING,
        db_index=True
    )
    
    # Metadata
    payment_method_id = models.CharField(
        max_length=255,
        blank=True,
        help_text="Stripe PaymentMethod ID"
    )
    
    locale = models.CharField(
        max_length=10,
        default='en',
        help_text="Language preference for receipts (en/es/fr/de)"
    )
    
    error_message = models.TextField(
        blank=True,
        help_text="Error details if payment failed"
    )
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    completed_at = models.DateTimeField(
        null=True,
        blank=True,
        help_text="When payment succeeded"
    )
    
    class Meta:
        app_label = 'payments'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['status', 'created_at']),
            models.Index(fields=['event', 'status']),
        ]
    
    def __str__(self):
        return f"Transaction {self.payment_intent_id} - {self.get_status_display()} (${self.amount})"
    
    @property
    def platform_revenue(self):
        """Calculate platform revenue from this transaction"""
        return self.application_fee_amount
    
    @property
    def tenant_revenue(self):
        """Calculate tenant revenue (amount minus platform fee)"""
        return self.amount - self.application_fee_amount
