from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from ..database import Base


class ReferralReward(Base):
    """레퍼럴 보상 모델"""
    __tablename__ = "referral_rewards"

    id = Column(Integer, primary_key=True, index=True)

    # 추천인 (보상 받는 사람)
    referrer_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)

    # 피추천인 (추천받아 가입한 사람)
    referred_user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)

    # 결제 금액 (피추천인이 충전한 금액 USD)
    payment_amount = Column(Float, nullable=False)

    # 보상 금액 (결제 금액의 X%)
    reward_amount = Column(Float, nullable=False)

    # 보상 상태: pending(대기), credited(적립), withdrawn(출금)
    status = Column(String(20), default="pending")

    # 출금 요청 ID (출금 시 연결)
    withdrawal_request_id = Column(Integer, ForeignKey("withdrawal_requests.id"), nullable=True)

    # 타임스탬프
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    credited_at = Column(DateTime(timezone=True), nullable=True)  # 적립 시각

    # Relationships
    referrer = relationship("User", foreign_keys=[referrer_id], backref="referral_rewards_given")
    referred_user = relationship("User", foreign_keys=[referred_user_id], backref="referral_rewards_received")
