from django.db import models
from uuid import uuid4


class MollieWebhookEvent(models.Model):
    """Durable idempotency record for a fetched Mollie payment state.

    Classic Mollie webhooks contain only a provider reference. The payload is
    deliberately not stored because it may contain customer data; the adapter
    retrieves the authoritative state from Mollie and records only a derived
    fingerprint plus operational outcome.
    """

    id = models.BigAutoField(primary_key=True)
    provider_reference = models.CharField(max_length=64)
    fingerprint = models.CharField(max_length=64)
    status = models.CharField(max_length=32)
    received_at = models.DateTimeField(auto_now_add=True)
    processed_at = models.DateTimeField(blank=True, null=True)
    failure_reason = models.CharField(max_length=255, blank=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=("provider_reference", "fingerprint"),
                name="payment_mollie_webhook_event_once",
            )
        ]
        ordering = ("-received_at",)


class MolliePaymentAttempt(models.Model):
    """An opaque checkout idempotency key, never a customer credential.

    The browser keeps the same key while retrying a single checkout redirect.
    Mollie receives that key through the official ``Idempotency-Key`` header,
    while this record gives operators a minimal local audit trail without
    storing request payloads or customer data.
    """

    id = models.BigAutoField(primary_key=True)
    order_number = models.CharField(max_length=128)
    method = models.CharField(max_length=64)
    idempotency_key = models.UUIDField(default=uuid4, unique=True, editable=False)
    provider_reference = models.CharField(max_length=64, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ("-created_at",)
