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

class Document(Base):
    __tablename__ = 'documents'

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True, nullable=False)
    text = Column(Text, nullable=False)
    source_url = Column(String, nullable=True)
    author = Column(String, nullable=True)
    status = Column(String, default="processing", nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    user_id = Column(String, index=True, nullable=True)
    
    vector_metadata = relationship(
        "VectorMetadata",
        back_populates="document",
        cascade="all, delete-orphan",
        uselist=False
    )

    def __repr__(self):
        return f"<Document(id={self.id}, title='{self.title}', user_id='{self.user_id}')>"

class VectorMetadata(Base):
    __tablename__ = 'vector_metadata'

    id = Column(Integer, primary_key=True, index=True)
    document_id = Column(Integer, ForeignKey('documents.id'), unique=True)
    session_id = Column(Integer, ForeignKey('sessions.id'), nullable=True)
    embedding_model = Column(String, nullable=False)

    document = relationship("Document", back_populates="vector_metadata")
    session = relationship("Session")

    def __repr__(self):
        return f"<VectorMetadata(id={self.id}, document_id={self.document_id}, session_id={self.session_id})>"
