from sqlalchemy import Float, ForeignKey, Index, String
from sqlalchemy.orm import Mapped, mapped_column

from app.models.base import Base, TimestampMixin


class CreditRecord(Base, TimestampMixin):
    __tablename__ = "credit_records"
    __table_args__ = (
        # 正式计费幂等键：同一用户同一个业务流水只能写入一次。
        # PostgreSQL/MySQL/SQLite 对 nullable unique 的处理都允许多条 NULL，兼容历史数据。
        Index("uq_credit_records_user_biz_key", "user_id", "biz_key", unique=True),
        Index("ix_credit_records_user_refund_for_biz_key", "user_id", "refund_for_biz_key"),
        Index("ix_credit_records_related_type", "related_id", "type"),
    )

    id: Mapped[str] = mapped_column(String(32), primary_key=True)
    user_id: Mapped[str] = mapped_column(
        String(32), ForeignKey("users.id", ondelete="CASCADE"), index=True
    )
    type: Mapped[str] = mapped_column(String(16))
    amount: Mapped[float] = mapped_column(Float)
    balance_after: Mapped[float] = mapped_column(Float)
    description: Mapped[str] = mapped_column(String(256))
    related_id: Mapped[str | None] = mapped_column(String(64), nullable=True)

    # 当前积分流水自己的业务幂等键。
    # 例如：generation_record:{record_id}:attempt:1:media:charge
    biz_key: Mapped[str | None] = mapped_column(String(160), nullable=True, index=True)

    # 如果当前流水是退款，记录它退的是哪一次扣费。
    # 例如：generation_record:{record_id}:attempt:1:media:charge
    refund_for_biz_key: Mapped[str | None] = mapped_column(String(160), nullable=True, index=True)
