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


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


class TableFlagDef(Base):
    """Manager-configurable flag definitions (name, emoji, color)."""
    __tablename__ = "table_flag_defs"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, nullable=False)
    emoji = Column(String, nullable=True)
    color = Column(String, nullable=True, default="#6b7280")  # hex background
    text_color = Column(String, nullable=True, default=None)  # hex text; None = white
    sort_order = Column(Integer, default=0, nullable=False)
    is_active = Column(Boolean, default=True, nullable=False)
    created_at = Column(DateTime(timezone=True), default=_utcnow)

    assignments = relationship("TableFlagAssignment", back_populates="flag_def", cascade="all, delete-orphan")


class TableFlagAssignment(Base):
    """Active flag on a specific table."""
    __tablename__ = "table_flag_assignments"

    id = Column(Integer, primary_key=True, index=True)
    table_id = Column(Integer, ForeignKey("tables.id"), nullable=False)
    flag_id = Column(Integer, ForeignKey("table_flag_defs.id"), nullable=False)
    assigned_at = Column(DateTime(timezone=True), default=_utcnow)
    assigned_by = Column(Integer, ForeignKey("users.id"), nullable=True)

    flag_def = relationship("TableFlagDef", back_populates="assignments")
    assigned_by_user = relationship("User")
