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

class RewardType(str, enum.Enum):
    discount = 'discount'
    room_upgrade = 'room_upgrade'
    amenity = 'amenity'
    cashback = 'cashback'
    voucher = 'voucher'

class RewardStatus(str, enum.Enum):
    available = 'available'
    redeemed = 'redeemed'
    expired = 'expired'

class LoyaltyReward(Base):
    __tablename__ = 'loyalty_rewards'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    name = Column(String(200), nullable=False)
    description = Column(Text, nullable=True)
    reward_type = Column(Enum(RewardType), nullable=False, index=True)
    points_cost = Column(Integer, nullable=False)
    discount_percentage = Column(Numeric(5, 2), nullable=True)
    discount_amount = Column(Numeric(10, 2), nullable=True)
    max_discount_amount = Column(Numeric(10, 2), nullable=True)
    applicable_tier_id = Column(Integer, ForeignKey('loyalty_tiers.id'), nullable=True)
    min_booking_amount = Column(Numeric(10, 2), nullable=True)
    icon = Column(String(255), nullable=True)
    image = Column(String(255), nullable=True)
    is_active = Column(Boolean, nullable=False, default=True)
    stock_quantity = Column(Integer, nullable=True)
    redeemed_count = Column(Integer, nullable=False, default=0)
    valid_from = Column(DateTime, nullable=True)
    valid_until = Column(DateTime, nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    # Relationships
    applicable_tier = relationship('LoyaltyTier', foreign_keys=[applicable_tier_id])
    redemptions = relationship('RewardRedemption', back_populates='reward')

    def is_available(self, user_tier_id=None, user_tier_min_points=None):
        """
        Check if reward is available for user
        
        Args:
            user_tier_id: User's current tier ID
            user_tier_min_points: User's tier minimum points (for tier level comparison)
        """
        from datetime import datetime
        now = datetime.utcnow()
        
        if not self.is_active:
            return False
        
        # If reward has a tier requirement, check if user's tier qualifies
        if self.applicable_tier_id:
            if user_tier_id is None:
                return False
            
            # Exact tier match - always allowed
            if user_tier_id == self.applicable_tier_id:
                pass  # Continue to other checks
            # If we have tier point info, allow users with higher tier level (more points)
            elif user_tier_min_points is not None and hasattr(self, '_required_tier_min_points'):
                # User tier must have equal or more minimum points (higher tier)
                if user_tier_min_points < self._required_tier_min_points:
                    return False
            else:
                # Without tier point info, use exact match only
                # Convert to int for comparison to avoid type mismatch issues
                try:
                    if int(user_tier_id) != int(self.applicable_tier_id):
                        return False
                except (ValueError, TypeError):
                    return False
        
        if self.valid_from and now < self.valid_from:
            return False
        if self.valid_until and now > self.valid_until:
            return False
        if self.stock_quantity is not None and self.redeemed_count >= self.stock_quantity:
            return False
        return True

