from sqlalchemy import Column, Integer, String, Numeric, Boolean, Text, DateTime, ForeignKey, Date
from sqlalchemy.orm import relationship
from datetime import datetime
from ...shared.config.database import Base

class UserLoyalty(Base):
    __tablename__ = 'user_loyalty'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey('users.id'), unique=True, nullable=False, index=True)
    tier_id = Column(Integer, ForeignKey('loyalty_tiers.id'), nullable=False, index=True)
    total_points = Column(Integer, nullable=False, default=0)
    lifetime_points = Column(Integer, nullable=False, default=0)
    available_points = Column(Integer, nullable=False, default=0)
    expired_points = Column(Integer, nullable=False, default=0)
    referral_code = Column(String(50), unique=True, nullable=True, index=True)
    referral_count = Column(Integer, nullable=False, default=0)
    birthday = Column(Date, nullable=True)
    anniversary_date = Column(Date, nullable=True)
    last_points_earned_date = Column(DateTime, nullable=True)
    tier_started_date = Column(DateTime, nullable=True)
    next_tier_points_needed = Column(Integer, nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    # Relationships
    user = relationship('User', back_populates='loyalty')
    tier = relationship('LoyaltyTier', back_populates='user_tiers')
    point_transactions = relationship('LoyaltyPointTransaction', back_populates='user_loyalty', cascade='all, delete-orphan')
    referrals = relationship('Referral', foreign_keys='Referral.referrer_id', back_populates='referrer')

