from sqlalchemy import Column, String, Text, DateTime, Boolean, ForeignKey, JSON
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from src.infrastructure.persistence.models.base import Base, TimestampMixin
import uuid

class ConversationModel(Base, TimestampMixin):
    __tablename__ = "conversations"
    
    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    user_id = Column(String(36), ForeignKey('users.id'), nullable=False)
    title = Column(String(255), nullable=False)
    is_active = Column(Boolean, default=True)
    
    # Relationships
    user = relationship("UserModel", back_populates="conversations")
    messages = relationship("ConversationMessageModel", back_populates="conversation", 
                          cascade="all, delete-orphan", order_by="ConversationMessageModel.timestamp")

class ConversationMessageModel(Base):
    __tablename__ = "conversation_messages"
    
    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    conversation_id = Column(String(36), ForeignKey("conversations.id"), nullable=False)
    sender_id = Column(String(36), nullable=False)  # user_id or system
    text = Column(Text, nullable=True)  
    chart_image_id = Column(String(36), nullable=True)  
    timestamp = Column(DateTime(timezone=True), server_default=func.now())
    #metadata = Column(JSON)  # For additional message data
    
    # Relationship
    conversation = relationship("ConversationModel", back_populates="messages")

class ConversationChartReferenceModel(Base):
    __tablename__ = "conversation_chart_references"
    
    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    conversation_id = Column(String(36), ForeignKey("conversations.id"), nullable=False)
    chart_image_id = Column(String(36), ForeignKey("chart_images.id"), nullable=False)
    added_at = Column(DateTime(timezone=True), server_default=func.now())
    
    # Relationships
    conversation = relationship("ConversationModel")
    chart_image = relationship("ChartImageModel")