"""Stripe webhook event ledger (B-2.8) — for idempotent processing.

Stripe delivers webhook events at least once. We record the event ID on
first successful processing; subsequent deliveries with the same ID are
no-op'd. Records are NOT garbage-collected automatically — operations
team can prune events older than 30 days if storage becomes a concern
(Stripe also has a 30-day delivery retry policy).
"""
from datetime import datetime
from src.database import db


class WebhookEvent(db.Model):
    """One row per processed Stripe webhook event."""
    __tablename__ = 'webhook_event'

    id = db.Column(db.Integer, primary_key=True)
    # Stripe event ID (`evt_xxx`) — primary dedup key
    stripe_event_id = db.Column(db.String(80), unique=True, nullable=False, index=True)
    event_type = db.Column(db.String(80), nullable=False, index=True)
    processed_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    # Optional: store the related stripe_subscription_id or stripe_customer_id
    # for fast lookup during incident debugging. Both nullable.
    stripe_subscription_id = db.Column(db.String(120), nullable=True, index=True)
    stripe_customer_id = db.Column(db.String(120), nullable=True, index=True)

    def __repr__(self):
        return f'<WebhookEvent {self.stripe_event_id} {self.event_type}>'
