from datetime import datetime from enum import Enum from typing import TYPE_CHECKING from sqlalchemy import DateTime, Enum as SAEnum, ForeignKey, Text, func from sqlalchemy.orm import Mapped, mapped_column, relationship from app.database.base import Base if TYPE_CHECKING: from app.chats.models import Chat from app.media.models import Attachment from app.users.models import User class MessageType(str, Enum): TEXT = "text" IMAGE = "image" VIDEO = "video" AUDIO = "audio" VOICE = "voice" FILE = "file" CIRCLE_VIDEO = "circle_video" class Message(Base): __tablename__ = "messages" id: Mapped[int] = mapped_column(primary_key=True, index=True) chat_id: Mapped[int] = mapped_column(ForeignKey("chats.id", ondelete="CASCADE"), nullable=False, index=True) sender_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True) type: Mapped[MessageType] = mapped_column(SAEnum(MessageType), nullable=False, default=MessageType.TEXT) text: Mapped[str | None] = mapped_column(Text, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False) updated_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False, ) chat: Mapped["Chat"] = relationship(back_populates="messages") sender: Mapped["User"] = relationship(back_populates="sent_messages") attachments: Mapped[list["Attachment"]] = relationship(back_populates="message", cascade="all, delete-orphan")