"""add feature_flags table

Revision ID: f1a2b3c4d5e6
Revises: e9c41b7d2f60
Create Date: 2026-10-06

Backs the admin on/off switch for general-purpose chat (HA ticket
2026-10-05). Shaped like quota_policies — scope_type plus a nullable
scope_id — so the global row ships now and a per-tenant override is an
INSERT later rather than a second migration.

Additive only: a new table, nothing existing is altered, so downgrade is a
clean drop.
"""
from alembic import op
import sqlalchemy as sa


revision = "f1a2b3c4d5e6"
down_revision = "e9c41b7d2f60"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "feature_flags",
        sa.Column("id", sa.Integer(), nullable=False),
        sa.Column("feature", sa.String(), nullable=False),
        sa.Column("scope_type", sa.String(), nullable=False,
                  server_default="global"),
        sa.Column("scope_id", sa.Integer(), nullable=True),
        sa.Column("enabled", sa.Boolean(), nullable=False,
                  server_default=sa.false()),
        sa.Column("updated_by", sa.Integer(), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True),
                  server_default=sa.text("now()"), nullable=True),
        sa.Column("updated_at", sa.DateTime(timezone=True),
                  server_default=sa.text("now()"), nullable=True),
        sa.PrimaryKeyConstraint("id"),
        # One row per (feature, scope): two disagreeing "global" rows would
        # make the toggle depend on insert order.
        sa.UniqueConstraint("feature", "scope_type", "scope_id",
                            name="uq_feature_flags_feature_scope"),
    )
    op.create_index(op.f("ix_feature_flags_id"), "feature_flags", ["id"])
    op.create_index(op.f("ix_feature_flags_feature"), "feature_flags", ["feature"])

    # Ships ENABLED (product decision, 2026-10-07): general chat is on as soon
    # as the migration runs. Turn it off per environment with
    # POST /admin/feature-flags/general_chat {"enabled": false}, or for good
    # with GENERAL_CHAT_MASTER_ENABLED=false.
    op.execute(
        "INSERT INTO feature_flags (feature, scope_type, scope_id, enabled) "
        "VALUES ('general_chat', 'global', NULL, true)"
    )


def downgrade() -> None:
    op.drop_index(op.f("ix_feature_flags_feature"), table_name="feature_flags")
    op.drop_index(op.f("ix_feature_flags_id"), table_name="feature_flags")
    op.drop_table("feature_flags")
