"""会员钱包模型"""
from decimal import Decimal
from datetime import datetime

from sqlalchemy import BigInteger, ForeignKey, String, DECIMAL, DateTime, text, Index
from sqlalchemy.orm import Mapped, mapped_column

from app.core.models.base import Base, TimestampMixin, TenantMixin


class CustomerWallet(Base, TenantMixin, TimestampMixin):
    """会员余额账户 — 一个客户对应一条记录"""

    __tablename__ = "customer_wallets"
    __table_args__ = (
        Index("ix_customer_wallets_tenant", "tenant_id"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    customer_id: Mapped[int] = mapped_column(
        BigInteger,
        ForeignKey("customers.id", ondelete="CASCADE"),
        nullable=False,
        unique=True,
    )
    balance: Mapped[Decimal] = mapped_column(
        DECIMAL(12, 2), nullable=False, server_default="0.00"
    )
    currency: Mapped[str] = mapped_column(String(8), nullable=False, server_default="NZD")

    def __repr__(self) -> str:
        return f"<CustomerWallet customer_id={self.customer_id} balance={self.balance}>"


class WalletTransaction(Base, TenantMixin):
    """余额变动明细"""

    __tablename__ = "wallet_transactions"
    __table_args__ = (
        Index("ix_wallet_transactions_tenant", "tenant_id"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    customer_id: Mapped[int] = mapped_column(
        BigInteger,
        ForeignKey("customers.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    amount: Mapped[Decimal] = mapped_column(
        DECIMAL(12, 2), nullable=False, comment="正=入账 负=扣款"
    )
    balance_after: Mapped[Decimal] = mapped_column(DECIMAL(12, 2), nullable=False)
    type: Mapped[str] = mapped_column(
        String(30), nullable=False,
        comment="topup / admin_adjust / order_pay / order_refund",
    )
    source_type: Mapped[str | None] = mapped_column(
        String(30), nullable=True, comment="order / admin / topup"
    )
    source_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
    note: Mapped[str | None] = mapped_column(String(500), nullable=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=False),
        nullable=False,
        server_default=text("CURRENT_TIMESTAMP"),
    )
