import uuid
from decimal import Decimal
from django.db import models
from django.conf import settings
from apps.core.models import BaseModel


class PaymentTransaction(BaseModel):
    STATUS_CHOICES = (
        ('created', 'Created'),
        ('pending', 'Pending'),
        ('success', 'Success'),
        ('failed', 'Failed'),
        ('refunded', 'Refunded'),
    )

    PROVIDER_CHOICES = (
        ('razorpay', 'Razorpay'),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='payments')
    provider = models.CharField(max_length=50, choices=PROVIDER_CHOICES, default='razorpay')
    provider_payment_id = models.CharField(max_length=255, blank=True, null=True, db_index=True)
    provider_order_id = models.CharField(max_length=255, blank=True, null=True, db_index=True)
    amount = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal('0.00'))
    currency = models.CharField(max_length=10, default='INR')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='created', db_index=True)
    payment_method = models.CharField(max_length=100, blank=True, null=True)
    completed_at = models.DateTimeField(null=True, blank=True)
    tenant_id = models.CharField(max_length=100, null=True, blank=True, db_index=True)

    class Meta:
        indexes = [
            models.Index(fields=['provider_order_id']),
            models.Index(fields=['provider_payment_id']),
            models.Index(fields=['status']),
        ]

    def __str__(self):
        return f"PaymentTransaction({self.id}) {self.status} {self.amount}{self.currency}"
