from sqlalchemy import Column, Integer, String, Boolean, DateTime, Index, UniqueConstraint, text
from sqlalchemy.sql import func
from database import Base


class FeatureFlag(Base):
    """A switch Product/Admin can throw without a deploy.

    Shaped like QuotaPolicy on purpose (scope_type + nullable scope_id):
    a row with scope_type="global" is the default everyone gets, and a
    scope_type="company" row overrides it for one tenant. The first feature
    to use this (general-purpose chat, HA ticket 2026-10-05) ships GLOBAL
    only, but the per-tenant shape is here from the start so enabling it for
    one company later is an INSERT rather than a migration plus a rewrite of
    the code that reads it.

    Deliberately a table and not an env var: the requirement is a button in
    the admin surface, and an env var needs a deploy to change, which is the
    thing a button exists to avoid. The env master kill-switch still exists
    alongside it — see feature_flag_service — for the case where engineering
    needs the capability off regardless of what the portal says.
    """

    __tablename__ = "feature_flags"
    __table_args__ = (
        # One row per (feature, scope). Without this, two "global" rows for
        # the same feature can disagree and which one wins depends on row
        # order — a toggle that works or not depending on insert history is
        # worse than no toggle.
        UniqueConstraint("feature", "scope_type", "scope_id",
                         name="uq_feature_flags_feature_scope"),
        # The constraint above does NOT cover the global row: its scope_id is
        # NULL and Postgres treats NULLs as distinct. This partial index does
        # (migration b8c9d0e1f2a3).
        Index("uq_feature_flags_global", "feature", "scope_type", unique=True,
              postgresql_where=text("scope_id IS NULL"),
              sqlite_where=text("scope_id IS NULL")),
    )

    id = Column(Integer, primary_key=True, index=True)

    feature = Column(String, nullable=False, index=True)   # e.g. "general_chat"

    scope_type = Column(String, nullable=False, default="global")  # "global" | "company"
    # NULL for "global"; the TENANT id (true_company_id) for "company".
    # Not the per-user company_id column seen elsewhere in this codebase,
    # which actually holds user_id — see models/hr_query_log.py.
    scope_id = Column(Integer, nullable=True)

    enabled = Column(Boolean, nullable=False, default=False)

    updated_by = Column(Integer, nullable=True)

    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now(), server_default=func.now())
