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

class ChatStatus(str, enum.Enum):
    pending = 'pending'
    active = 'active'
    closed = 'closed'

class Chat(Base):
    __tablename__ = 'chats'
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    visitor_id = Column(Integer, ForeignKey('users.id'), nullable=True)
    visitor_name = Column(String(100), nullable=True)
    visitor_email = Column(String(100), nullable=True)
    staff_id = Column(Integer, ForeignKey('users.id'), nullable=True)
    status = Column(Enum(ChatStatus), nullable=False, default=ChatStatus.pending)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    closed_at = Column(DateTime, nullable=True)
    visitor = relationship('User', foreign_keys=[visitor_id], back_populates='visitor_chats')
    staff = relationship('User', foreign_keys=[staff_id], back_populates='staff_chats')
    messages = relationship('ChatMessage', back_populates='chat', cascade='all, delete-orphan', order_by='ChatMessage.created_at')

class ChatMessage(Base):
    __tablename__ = 'chat_messages'
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    chat_id = Column(Integer, ForeignKey('chats.id'), nullable=False)
    sender_id = Column(Integer, ForeignKey('users.id'), nullable=True)
    sender_type = Column(String(20), nullable=False)
    message = Column(Text, nullable=False)
    is_read = Column(Boolean, nullable=False, default=False)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    chat = relationship('Chat', back_populates='messages')
    sender = relationship('User', foreign_keys=[sender_id])