import pytest

from app.services.integrations.platform import strip_tenant_prefix


def test_strips_the_org_prefix():
    assert strip_tenant_prefix("org_8c32bf3e-6a18-4739-9b1c-94c0cf11125f") == \
        "8c32bf3e-6a18-4739-9b1c-94c0cf11125f"


@pytest.mark.parametrize("bad", [
    "8c32bf3e-6a18-4739-9b1c-94c0cf11125f",   # no prefix
    "org_not-a-uuid",
    "org_",
    "",
    None,
    "tenant_8c32bf3e-6a18-4739-9b1c-94c0cf11125f",
])
def test_rejects_anything_that_is_not_a_prefixed_uuid(bad):
    # The value goes into a uuid column with a foreign key; a malformed one must
    # fail here rather than as a database error halfway through a callback.
    with pytest.raises(ValueError):
        strip_tenant_prefix(bad)


def test_track_connect_survives_a_dead_database(monkeypatch):
    # An audit row must never be why a merchant's connection fails.
    import app.services.integrations.platform as mod

    def boom():
        raise RuntimeError("master db unreachable")

    monkeypatch.setattr(mod, "get_master_db_connection", boom)
    mod.track_connect("org_8c32bf3e-6a18-4739-9b1c-94c0cf11125f", "shopify",
                      "connected", "success")   # must not raise


def test_platform_config_is_cached(monkeypatch):
    # verify_hmac calls this on every OAuth callback; an uncached lookup
    # against a dead master DB stalls the callback for ~34 seconds.
    import app.services.integrations.platform as mod
    mod._config_cache.clear()
    calls = []

    class FakeCur:
        def __enter__(self): return self
        def __exit__(self, *a): return False
        def execute(self, *a): calls.append(1)
        def fetchone(self): return None

    class FakeConn:
        def cursor(self, **kw): return FakeCur()
        def close(self): pass

    monkeypatch.setattr(mod, "get_master_db_connection", lambda: FakeConn())
    mod.get_platform_config("shopify")
    mod.get_platform_config("shopify")
    assert len(calls) == 1, "a second call within the TTL must not query again"
