import pytest
from unittest.mock import AsyncMock, patch

from app.core.config import settings
from app.services.upload_service import UploadService


@pytest.mark.asyncio
async def test_ensure_indexes_on_startup_swallows_mongo_error_in_local():
    service = UploadService()

    with (
        patch.object(service._repos, "ensure_indexes", AsyncMock(side_effect=ConnectionError("refused"))),
        patch.object(type(settings), "is_local", return_value=True),
    ):
        await service.ensure_indexes_on_startup()

    assert service._indexes_ready is False


@pytest.mark.asyncio
async def test_ensure_indexes_on_startup_raises_in_production():
    service = UploadService()

    with (
        patch.object(service._repos, "ensure_indexes", AsyncMock(side_effect=ConnectionError("refused"))),
        patch.object(type(settings), "is_local", return_value=False),
    ):
        with pytest.raises(ConnectionError):
            await service.ensure_indexes_on_startup()
