import enum

from sqlalchemy import BigInteger, ForeignKey, Integer, String
from sqlalchemy import Enum as SAEnum
from sqlalchemy.orm import Mapped, mapped_column

from app.models.base import BaseModel


class BalanceChangeType(str, enum.Enum):
    RECHARGE = "recharge"           # 充值到账
    ADMIN_ADJUST = "admin_adjust"   # 管理员调账
    ORDER_PAY = "order_pay"         # 订单扣款（预留）
    ORDER_REFUND = "order_refund"   # 订单退款（预留）
    RECHARGE_REFUND = "recharge_refund"  # 充值退款（预留）


class BalanceLog(BaseModel):
    """余额流水。每次余额变动写一条，不可修改，作为资金审计依据。"""

    __tablename__ = "balance_logs"

    user_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
    )

    change_type: Mapped[BalanceChangeType] = mapped_column(
        SAEnum(BalanceChangeType, values_callable=lambda e: [m.value for m in e]),
        nullable=False,
        index=True,
    )

    # 变动金额（分），正数为入账，负数为扣款
    delta: Mapped[int] = mapped_column(Integer, nullable=False, comment="变动金额，单位分，正入负出")

    # 变动后余额快照（分），便于对账
    balance_after: Mapped[int] = mapped_column(Integer, nullable=False, comment="变动后余额，单位分")

    # 关联业务单号（充值订单 out_trade_no / 订单号等）
    ref_no: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)

    # 操作人（管理员调账时记录管理员 ID）
    operator_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True)

    remark: Mapped[str | None] = mapped_column(String(255), nullable=True)
