import pytest

from backend.app.models import TagKind
from backend.app.services.tag_service import TagService, TagValidationError

pytestmark = pytest.mark.integration


@pytest.mark.asyncio
async def test_rename_success(db):
    svc = TagService(db)
    t = await svc.find_or_create("uchiha_sasuke", TagKind.character)
    renamed = await svc.rename(t.id, "Sasuke Uchiha")
    assert renamed.id == t.id
    assert renamed.name == "Sasuke Uchiha"


@pytest.mark.asyncio
async def test_rename_collision_raises(db):
    svc = TagService(db)
    await svc.find_or_create("Existing", TagKind.character)
    other = await svc.find_or_create("Other", TagKind.character)
    with pytest.raises(TagValidationError, match="already exists"):
        await svc.rename(other.id, "Existing")


@pytest.mark.asyncio
async def test_rename_same_name_different_kind_ok(db):
    svc = TagService(db)
    await svc.find_or_create("Shared", TagKind.character)
    artist = await svc.find_or_create("ArtistTag", TagKind.artist)
    renamed = await svc.rename(artist.id, "Shared")
    assert renamed.name == "Shared"


@pytest.mark.asyncio
async def test_rename_empty_raises(db):
    svc = TagService(db)
    t = await svc.find_or_create("Whatever", TagKind.general)
    with pytest.raises(TagValidationError):
        await svc.rename(t.id, "   ")
