import uuid
from django.db import models
from django.conf import settings
from core.models import TimeStampedModel


class Payment(TimeStampedModel):
    """
    Records a Paystack payment. Used for both booking fees and order checkouts.
    The two-step verification rule: webhook signature check + server-to-server
    Transaction Verify before any state change.
    """
    TYPE_CHOICES = [
        ('booking_fee', 'Booking Fee'),
        ('order_checkout', 'Order Checkout'),
    ]

    STATUS_CHOICES = [
        ('initiated', 'Initiated'),
        ('verified', 'Verified'),
        ('failed', 'Failed'),
    ]

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    type = models.CharField(max_length=20, choices=TYPE_CHOICES)
    paystack_reference = models.CharField(max_length=200, unique=True)
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='initiated')
    verified_at = models.DateTimeField(null=True, blank=True)
    raw_webhook_payload = models.JSONField(default=dict, blank=True)
    metadata = models.JSONField(
        default=dict, blank=True,
        help_text='Additional context passed to/from Paystack (e.g., booking details, order ID).'
    )

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.get_type_display()} - {self.paystack_reference} ({self.status})"

    @property
    def is_verified(self):
        return self.status == 'verified'
