from dashboard_widget_entitlements import widget_id_allowed


def test_multi_feature_and_requires_all(monkeypatch):
    wid = "nutrition_detail_charts"

    def fake_check(pid, fid, conn):
        return {"allowed": fid in ("a", "b")}

    monkeypatch.setattr(
        "dashboard_widget_entitlements.get_widget_required_feature_ids",
        lambda w, conn: ["a", "b"] if w == wid else [],
    )
    monkeypatch.setattr("dashboard_widget_entitlements._check_feature_access", fake_check)
    assert widget_id_allowed(wid, "p", object()) is True

    def fake_check_one_denied(pid, fid, conn):
        return {"allowed": fid == "a"}

    monkeypatch.setattr("dashboard_widget_entitlements._check_feature_access", fake_check_one_denied)
    assert widget_id_allowed(wid, "p", object()) is False


def test_no_features_required_always_allowed(monkeypatch):
    monkeypatch.setattr(
        "dashboard_widget_entitlements.get_widget_required_feature_ids",
        lambda wid, conn: [],
    )
    assert widget_id_allowed("welcome", "p", object()) is True


def test_unknown_widget_not_allowed():
    assert widget_id_allowed("not_in_catalog", "p", object()) is False


def test_get_widget_required_catalog_fallback(monkeypatch):
    from widget_feature_requirements_db import get_widget_required_feature_ids

    class _Cur:
        def execute(self, *a, **k):
            pass

        def fetchone(self):
            return None

    monkeypatch.setattr("widget_feature_requirements_db.get_cursor", lambda _c: _Cur())
    assert get_widget_required_feature_ids("quick_capture", object()) == ["weight_entries"]
