"""
付款記錄 Model
記錄所有付款交易
"""
from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, Numeric, ForeignKey, Text
from sqlalchemy.orm import relationship
import enum

from app.db.base import Base


class PaymentStatus(str, enum.Enum):
    """付款狀態"""
    SUCCESS = "success"       # 成功
    FAILED = "failed"         # 失敗
    PENDING = "pending"       # 處理中
    REFUNDED = "refunded"     # 已退款


class Payment(Base):
    """付款記錄表"""

    __tablename__ = "payments"

    id = Column(Integer, primary_key=True, index=True)
    invoice_id = Column(Integer, ForeignKey("invoices.id", ondelete="CASCADE"), nullable=False, index=True)
    tenant_id = Column(Integer, ForeignKey("organizes.id", ondelete="CASCADE"), nullable=False, index=True)

    # 付款資訊
    amount = Column(Numeric(10, 2), nullable=False, comment="付款金額")
    payment_method = Column(String(20), nullable=False, comment="付款方式 (credit_card/wire_transfer/cash)")
    transaction_id = Column(String(100), nullable=True, comment="金流交易編號")
    status = Column(String(20), default=PaymentStatus.PENDING, nullable=False, comment="狀態")

    # 時間記錄
    paid_at = Column(DateTime, default=datetime.utcnow, nullable=False, comment="付款時間")

    # 備註
    notes = Column(Text, nullable=True, comment="備註")

    # 關聯
    invoice = relationship("Invoice", back_populates="payments")

    def __repr__(self):
        return f"<Payment NT$ {self.amount} - {self.status}>"

    @property
    def is_success(self) -> bool:
        """是否付款成功"""
        return self.status == PaymentStatus.SUCCESS
