"""Tests for app.services.tag_loader — batch tag loader"""

import pytest
from unittest.mock import AsyncMock, MagicMock, patch


UUID_1 = "550e8400-e29b-41d4-a716-446655440000"
UUID_2 = "550e8400-e29b-41d4-a716-446655440001"
TAG_UUID_1 = "660e8400-e29b-41d4-a716-446655440000"
TAG_UUID_2 = "660e8400-e29b-41d4-a716-446655440001"


@pytest.mark.asyncio
async def test_load_tags_empty_ids():
    """Empty literature_ids returns empty dict"""
    from app.services.tag_loader import load_tags_for_literature
    db = AsyncMock()
    result = await load_tags_for_literature(db, [])
    assert result == {}
    db.execute.assert_not_called()


@pytest.mark.asyncio
async def test_load_tags_no_results():
    """No tags found returns empty dict"""
    from app.services.tag_loader import load_tags_for_literature

    mock_result = MagicMock()
    mock_result.__iter__.return_value = []

    mock_db = AsyncMock()
    mock_db.execute.return_value = mock_result

    result = await load_tags_for_literature(mock_db, [UUID_1])
    assert result == {}
    mock_db.execute.assert_called_once()


@pytest.mark.asyncio
async def test_load_tags_one_lit_one_tag():
    """One literature item with one tag"""
    from app.services.tag_loader import load_tags_for_literature

    mock_result = MagicMock()
    mock_result.__iter__.return_value = [
        (UUID_1, TAG_UUID_1, "Neoplasms", "C04", "cancer", True),
    ]

    mock_db = AsyncMock()
    mock_db.execute.return_value = mock_result

    result = await load_tags_for_literature(mock_db, [UUID_1])
    assert UUID_1 in result
    assert len(result[UUID_1]) == 1
    assert result[UUID_1][0]["id"] == TAG_UUID_1
    assert result[UUID_1][0]["name_zh"] == "Neoplasms"
    assert result[UUID_1][0]["is_major"] is True


@pytest.mark.asyncio
async def test_load_tags_multiple_lits():
    """Multiple literature items return grouped results"""
    from app.services.tag_loader import load_tags_for_literature

    mock_result = MagicMock()
    mock_result.__iter__.return_value = [
        (UUID_1, TAG_UUID_1, "Neoplasms", "C04", "cancer", True),
        (UUID_1, TAG_UUID_2, "Lung", "C04.123", "cancer", False),
        (UUID_2, TAG_UUID_1, "EGFR", "A01", "gene", False),
    ]

    mock_db = AsyncMock()
    mock_db.execute.return_value = mock_result

    result = await load_tags_for_literature(mock_db, [UUID_1, UUID_2])
    assert len(result[UUID_1]) == 2
    assert len(result[UUID_2]) == 1
    assert result[UUID_2][0]["name_zh"] == "EGFR"


@pytest.mark.asyncio
async def test_load_tags_uuid_conversion():
    """String UUIDs are converted to UUID objects for the query"""
    from app.services.tag_loader import load_tags_for_literature

    mock_result = MagicMock()
    mock_result.__iter__.return_value = []

    mock_db = AsyncMock()
    mock_db.execute.return_value = mock_result

    await load_tags_for_literature(mock_db, [UUID_1])
    # Verify the query was executed (UUID conversion didn't crash)
    mock_db.execute.assert_called_once()
