"""标签 CRUD 单元测试（使用 InMemoryTagRepository）。"""

import pytest

from packages.adapters.in_memory.tag_repository import InMemoryTagRepository
from packages.domain import Tag


@pytest.fixture
def tag_repo():
    return InMemoryTagRepository()


def test_create_tag(tag_repo):
    """测试创建标签。"""
    tag = Tag.create(user_id="user-1", name="风景")
    created = tag_repo.create(tag)

    assert created.id == tag.id
    assert created.user_id == "user-1"
    assert created.name == "风景"


def test_create_tag_strips_whitespace(tag_repo):
    """测试创建标签时自动去除首尾空格。"""
    tag = Tag.create(user_id="user-1", name="  风景  ")
    assert tag.name == "风景"


def test_create_tag_empty_name_raises():
    """测试空名称抛出 ValueError。"""
    with pytest.raises(ValueError, match="标签名称不能为空"):
        Tag.create(user_id="user-1", name="")

    with pytest.raises(ValueError, match="标签名称不能为空"):
        Tag.create(user_id="user-1", name="   ")


def test_get_tag(tag_repo):
    """测试按 ID 获取标签。"""
    tag = Tag.create(user_id="user-1", name="风景")
    tag_repo.create(tag)

    found = tag_repo.get(tag.id)
    assert found is not None
    assert found.name == "风景"

    assert tag_repo.get("nonexistent") is None


def test_find_by_name(tag_repo):
    """测试按用户 ID + 名称查找标签。"""
    tag = Tag.create(user_id="user-1", name="风景")
    tag_repo.create(tag)

    found = tag_repo.find_by_name("user-1", "风景")
    assert found is not None
    assert found.id == tag.id

    # 不同用户同名标签不冲突
    assert tag_repo.find_by_name("user-2", "风景") is None

    # 不存在的名称
    assert tag_repo.find_by_name("user-1", "不存在") is None


def test_list_by_user(tag_repo):
    """测试按用户列出标签（分页）。"""
    for i in range(5):
        tag_repo.create(Tag.create(user_id="user-1", name=f"标签{i}"))
    # 另一个用户的标签
    tag_repo.create(Tag.create(user_id="user-2", name="其他用户标签"))

    items = tag_repo.list_by_user("user-1")
    assert len(items) == 5

    # 分页
    items_page = tag_repo.list_by_user("user-1", skip=2, limit=2)
    assert len(items_page) == 2


def test_count_by_user(tag_repo):
    """测试按用户统计标签数量。"""
    for i in range(3):
        tag_repo.create(Tag.create(user_id="user-1", name=f"标签{i}"))
    tag_repo.create(Tag.create(user_id="user-2", name="其他"))

    assert tag_repo.count_by_user("user-1") == 3
    assert tag_repo.count_by_user("user-2") == 1
    assert tag_repo.count_by_user("user-3") == 0


def test_delete_tag(tag_repo):
    """测试删除标签。"""
    tag = Tag.create(user_id="user-1", name="风景")
    tag_repo.create(tag)

    assert tag_repo.delete(tag.id) is True
    assert tag_repo.get(tag.id) is None

    # 重复删除返回 False
    assert tag_repo.delete(tag.id) is False
