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


def _utcnow():
    return datetime.now(timezone.utc)


class QuickMessageTemplate(Base):
    """Manager-configurable quick message templates."""
    __tablename__ = "quick_message_templates"

    id = Column(Integer, primary_key=True, index=True)
    body = Column(String, nullable=False)
    sort_order = Column(Integer, default=0, nullable=False)
    is_active = Column(Boolean, default=True, nullable=False)
    created_at = Column(DateTime(timezone=True), default=_utcnow)


class StaffMessage(Base):
    """A message sent from a manager to one or more waiters."""
    __tablename__ = "staff_messages"

    id = Column(Integer, primary_key=True, index=True)
    sender_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    body = Column(Text, nullable=False)
    # JSON arrays stored as text: "[1,2,3]" for waiter ids, "[5,6]" for table ids
    target_waiter_ids = Column(Text, nullable=False, default="[]")
    table_ids = Column(Text, nullable=False, default="[]")
    created_at = Column(DateTime(timezone=True), default=_utcnow)

    sender = relationship("User", foreign_keys=[sender_id])
    acks = relationship("StaffMessageAck", back_populates="message", cascade="all, delete-orphan")


class StaffMessageAck(Base):
    """Acknowledgement by a specific waiter for a specific message."""
    __tablename__ = "staff_message_acks"

    id = Column(Integer, primary_key=True, index=True)
    message_id = Column(Integer, ForeignKey("staff_messages.id"), nullable=False)
    waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    acked_at = Column(DateTime(timezone=True), default=_utcnow)

    message = relationship("StaffMessage", back_populates="acks")
    waiter = relationship("User")
