import uuid
from datetime import datetime
from sqlalchemy import String, DateTime, ForeignKey, Index
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.sql import func
from app.database import Base

class Document(Base):
    '''
    Represents the DocumentEnvelope.
    Implements ADR-001: Separation of Metadata and Payload.
    '''
    __tablename__ = "documents"

    id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
    authority_id: Mapped[str] = mapped_column(String(50), index=True)
    reference_number: Mapped[str] = mapped_column(String(50))
    doc_type: Mapped[str] = mapped_column(String(20))
    storage_path: Mapped[str] = mapped_column(String(255)) 
    status: Mapped[str] = mapped_column(String(20), default="RECEIVED")
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
    retention_date: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=True)

    threads = relationship("InteractionThread", back_populates="document")

class InteractionThread(Base):
    __tablename__ = "threads"

    id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
    document_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("documents.id"))
    type: Mapped[str] = mapped_column(String(20))
    status: Mapped[str] = mapped_column(String(20), default="OPEN")
    
    document = relationship("Document", back_populates="threads")
    messages = relationship("Message", back_populates="thread")

class Message(Base):
    '''
    Optimized for Cursor-Based Pagination (NFR-1).
    '''
    __tablename__ = "messages"

    id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
    thread_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("threads.id"))
    sender_role: Mapped[str] = mapped_column(String(20))
    content_blob: Mapped[str] = mapped_column(String) 
    timestamp: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())

    thread = relationship("InteractionThread", back_populates="messages")

    __table_args__ = (
        Index('idx_msgs_thread_time', 'thread_id', 'timestamp'),
    )