from decimal import Decimal
from sqlalchemy import BigInteger, String, JSON, DECIMAL, UniqueConstraint, Index, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.core.models.base import Base, TimestampMixin


class Payment(Base, TimestampMixin):
    """支付记录（支持多网关：Stripe / 微信支付 / 银行转账）"""

    __tablename__ = "payments"
    __table_args__ = (
        UniqueConstraint("gateway_ref", name="uk_payment_gateway_ref"),
        Index("ix_payment_order", "order_id"),
        Index("ix_payment_gateway", "gateway"),
        Index("ix_payment_status", "status"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    order_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("orders.id", ondelete="RESTRICT"), nullable=False)
    tenant_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("tenants.id", ondelete="RESTRICT"), nullable=False, index=True)
    gateway: Mapped[str] = mapped_column(String(50), nullable=False, comment="stripe / wechat_pay / bank_transfer")
    amount: Mapped[Decimal] = mapped_column(DECIMAL(12, 2), nullable=False)
    currency: Mapped[str] = mapped_column(String(3), nullable=False, default="NZD")
    status: Mapped[str] = mapped_column(String(30), nullable=False, comment="pending/completed/failed/refunded")
    gateway_ref: Mapped[str | None] = mapped_column(String(200), nullable=True, comment="第三方流水号（如 Stripe PaymentIntent ID）")
    extra_data: Mapped[dict | None] = mapped_column(JSON, nullable=True, comment="网关原始回调 JSON，用于对账")

    order = relationship("Order", back_populates="payments", lazy="noload")

    def __repr__(self) -> str:
        return f"<Payment id={self.id} gateway={self.gateway!r} status={self.status!r}>"
