"""Rewarded-advertisement analytics event stream.

Append-only event table backing rewarded-ad analytics — one row per meaningful
rewarded-ad event (impression, video playback, reward grant/rejection). It mirrors
the existing :class:`app.models.marketplace.ListingView` pattern: raw, un-summarised
rows so completion rate, rejection breakdown and video-playback stats are simple
``GROUP BY`` queries, without bloating the ``advertisements`` row with a dozen
counters or double-counting against the shared ``impression_count`` column.

Privacy: no IP address, user agent or cryptographic material is stored — only the
acting user id, the advertisement id, a coarse event type and (for rejections) a
coarse reason. Aggregation lives in :mod:`app.admin.advertisements.services`.
"""

from __future__ import annotations

from app.extensions import db
from app.models.base import BaseModel, BigIntegerType, utcnow


class RewardedAdEvent(BaseModel):
    """A single rewarded-advertisement analytics event."""

    __tablename__ = "rewarded_ad_events"
    __table_args__ = (
        db.Index("ix_rewarded_ad_events_advertisement_id", "advertisement_id"),
        db.Index("ix_rewarded_ad_events_event_type", "event_type"),
        db.Index("ix_rewarded_ad_events_created_at", "created_at"),
    )

    # Nullable: the built-in placeholder ad has no advertisements row.
    advertisement_id = db.Column(BigIntegerType, db.ForeignKey("advertisements.id"), nullable=True)
    # The authenticated participant the event belongs to (nullable defensively).
    user_id = db.Column(BigIntegerType, db.ForeignKey("users.id"), nullable=True)
    # One of the EVENT_* constants in app.advertisements.reward_analytics.
    event_type = db.Column(db.String(32), nullable=False)
    # Coarse reason for ``reward_rejected`` events (expired/replay/tampered/…).
    reason = db.Column(db.String(32), nullable=True)
    created_at = db.Column(db.DateTime(timezone=True), nullable=False, default=utcnow)

    def __repr__(self) -> str:
        return f"<RewardedAdEvent id={self.id} type={self.event_type!r} ad={self.advertisement_id}>"
