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

# Association table for many-to-many relationship between users and segments
guest_segment_association = Table(
    'guest_segment_associations',
    Base.metadata,
    Column('user_id', Integer, ForeignKey('users.id'), primary_key=True),
    Column('segment_id', Integer, ForeignKey('guest_segments.id'), primary_key=True),
    Column('assigned_at', DateTime, default=datetime.utcnow, nullable=False)
)

class GuestSegment(Base):
    __tablename__ = 'guest_segments'
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    name = Column(String(100), unique=True, nullable=False, index=True)
    description = Column(Text, nullable=True)
    criteria = Column(JSON, nullable=True)  # JSON object defining segment criteria
    is_active = Column(Boolean, nullable=False, default=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    users = relationship('User', secondary=guest_segment_association, back_populates='guest_segments')

