"""The on/off switch for general-purpose chat.

Two controls, and the ordering between them is the point: the DB row is the
business control (a button, no deploy), the env var is the engineering
kill-switch, and master wins. A kill-switch a database row can override is
not a kill-switch.

Everything fails CLOSED. A missing row, an unreadable row, a database that
cannot be reached — all answer "disabled". An outage must never be able to
switch a capability ON.
"""
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from database import Base
from models.feature_flag import FeatureFlag
import services.feature_flag_service as ff


@pytest.fixture
def db():
    """A throwaway SQLite database — never the real one."""
    engine = create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine, tables=[FeatureFlag.__table__])
    session = sessionmaker(bind=engine)()
    try:
        yield session
    finally:
        session.close()


@pytest.fixture(autouse=True)
def master_on(monkeypatch):
    monkeypatch.setenv("GENERAL_CHAT_MASTER_ENABLED", "true")


# ── default state ───────────────────────────────────────────────────────────

def test_no_row_means_disabled(db):
    """A deployment that configures nothing behaves exactly as it does
    today. This is what makes "flag off == unchanged" true by default."""
    assert ff.is_enabled(db) is False


def test_a_global_row_decides(db):
    ff.set_enabled(db, ff.GENERAL_CHAT, True)
    assert ff.is_enabled(db) is True

    ff.set_enabled(db, ff.GENERAL_CHAT, False)
    assert ff.is_enabled(db) is False


def test_setting_twice_updates_one_row(db):
    """Not two rows that disagree — which is what the unique constraint is
    for, and why set_enabled looks the row up before inserting."""
    ff.set_enabled(db, ff.GENERAL_CHAT, True)
    ff.set_enabled(db, ff.GENERAL_CHAT, False)
    rows = db.query(FeatureFlag).filter(FeatureFlag.feature == ff.GENERAL_CHAT).all()
    assert len(rows) == 1
    assert rows[0].enabled is False


# ── the master kill-switch ──────────────────────────────────────────────────

def test_master_off_beats_an_enabled_row(db, monkeypatch):
    """The engineering override. If this ever stops holding, the kill-switch
    is decorative."""
    ff.set_enabled(db, ff.GENERAL_CHAT, True)
    assert ff.is_enabled(db) is True

    monkeypatch.setenv("GENERAL_CHAT_MASTER_ENABLED", "false")
    assert ff.is_enabled(db) is False


@pytest.mark.parametrize("value", ["false", "0", "no", "off", "FALSE", "Off"])
def test_master_off_spellings(db, monkeypatch, value):
    ff.set_enabled(db, ff.GENERAL_CHAT, True)
    monkeypatch.setenv("GENERAL_CHAT_MASTER_ENABLED", value)
    assert ff.is_enabled(db) is False


def test_master_is_read_per_call_not_at_import(db, monkeypatch):
    """Flipping the env var takes effect without a restart — the reason this
    is not a module-level constant like QUERY_CACHE_ENABLED."""
    ff.set_enabled(db, ff.GENERAL_CHAT, True)
    monkeypatch.setenv("GENERAL_CHAT_MASTER_ENABLED", "false")
    assert ff.is_enabled(db) is False
    monkeypatch.setenv("GENERAL_CHAT_MASTER_ENABLED", "true")
    assert ff.is_enabled(db) is True


# ── per-tenant scope (shipped global, shape ready) ──────────────────────────

def test_a_company_row_overrides_the_global_one(db):
    ff.set_enabled(db, ff.GENERAL_CHAT, False)
    ff.set_enabled(db, ff.GENERAL_CHAT, True, company_id=42)

    assert ff.is_enabled(db) is False                      # global
    assert ff.is_enabled(db, company_id=42) is True        # that tenant
    assert ff.is_enabled(db, company_id=99) is False       # any other tenant


def test_a_tenant_with_no_row_follows_the_global_one(db):
    ff.set_enabled(db, ff.GENERAL_CHAT, True)
    assert ff.is_enabled(db, company_id=12345) is True


# ── failing closed ──────────────────────────────────────────────────────────

def test_an_unreachable_database_reads_as_disabled(db, monkeypatch):
    """The important direction. A DB wobble must not switch the capability
    ON, and nobody is harmed by general chat being briefly unavailable."""
    class Broken:
        def query(self, *a, **k):
            raise RuntimeError("database is down")

    assert ff.is_enabled(Broken()) is False


# ── what the admin surface reports ──────────────────────────────────────────

def test_describe_surfaces_the_master_switch(db, monkeypatch):
    """A row reading enabled=true while the capability is off looks like a
    bug unless the override is visible, so describe() reports both."""
    ff.set_enabled(db, ff.GENERAL_CHAT, True)
    monkeypatch.setenv("GENERAL_CHAT_MASTER_ENABLED", "false")

    out = ff.describe(db)
    assert out["master_enabled"] is False
    assert out["effective_global"] is False
    assert out["scopes"][0]["enabled"] is True      # the row still says true


# -- Review fixes -------------------------------------------------------------

def test_a_second_global_row_cannot_be_inserted(db):
    """The unique constraint alone did not stop it: the global row's scope_id
    is NULL and NULLs are distinct. The partial index does."""
    from sqlalchemy.exc import IntegrityError
    db.add(FeatureFlag(feature=ff.GENERAL_CHAT, scope_type=ff.GLOBAL_SCOPE, scope_id=None, enabled=False))
    db.commit()
    db.add(FeatureFlag(feature=ff.GENERAL_CHAT, scope_type=ff.GLOBAL_SCOPE, scope_id=None, enabled=True))
    with pytest.raises(IntegrityError):
        db.commit()
    db.rollback()


def test_company_rows_for_different_tenants_coexist(db):
    ff.set_enabled(db, ff.GENERAL_CHAT, True, company_id=7)
    ff.set_enabled(db, ff.GENERAL_CHAT, False, company_id=8)
    ff.set_enabled(db, ff.GENERAL_CHAT, True)
    assert ff.is_enabled(db, company_id=7) is True
    assert ff.is_enabled(db, company_id=8) is False


def test_setting_the_global_row_twice_updates_it(db):
    ff.set_enabled(db, ff.GENERAL_CHAT, True)
    ff.set_enabled(db, ff.GENERAL_CHAT, False)
    assert db.query(FeatureFlag).filter(FeatureFlag.scope_id.is_(None)).count() == 1
    assert ff.is_enabled(db) is False


def test_an_unknown_feature_is_a_404():
    """A typo in the path must not create a row nothing reads."""
    from fastapi import HTTPException
    import routers.admin_feature_flags as r
    with pytest.raises(HTTPException) as exc:
        r._known("genral_chat")
    assert exc.value.status_code == 404
    assert r._known(ff.GENERAL_CHAT) == ff.GENERAL_CHAT
