"""Per-platform download concurrency cap (Redis lock)."""
import pytest

from backend.app.services.platform_lock import platform_lock

# Needs the broker (Redis) the lock lives in.
pytestmark = pytest.mark.integration


def test_non_serialized_platform_has_no_lock():
    # gallery-dl platforms aren't capped — they get no lock at all.
    assert platform_lock("hentaifoundry", ttl_seconds=60) is None
    assert platform_lock("discord", ttl_seconds=60) is None


def test_subscribestar_is_serialized():
    # subscribestar is a native-ingester platform now — one paced walk at a time.
    lock = platform_lock("subscribestar", ttl_seconds=60)
    assert lock is not None


def test_patreon_serializes_to_one_holder():
    first = platform_lock("patreon", ttl_seconds=60)
    assert first is not None
    assert first.acquire(blocking=False) is True
    try:
        # A second acquirer is refused while the first holds it.
        second = platform_lock("patreon", ttl_seconds=60)
        assert second.acquire(blocking=False) is False
    finally:
        first.release()

    # Once released, the platform is acquirable again.
    third = platform_lock("patreon", ttl_seconds=60)
    assert third.acquire(blocking=False) is True
    third.release()
