"""标签 InMemory 仓储实现。"""

from packages.domain import Tag


class InMemoryTagRepository:
    def __init__(self):
        self._tags: dict[str, Tag] = {}

    def create(self, tag: Tag) -> Tag:
        self._tags[tag.id] = tag
        return tag

    def get(self, tag_id: str) -> Tag | None:
        return self._tags.get(tag_id)

    def find_by_name(self, user_id: str, name: str) -> Tag | None:
        for tag in self._tags.values():
            if tag.user_id == user_id and tag.name == name:
                return tag
        return None

    def list_by_user(
        self,
        user_id: str,
        skip: int = 0,
        limit: int = 100,
    ) -> list[Tag]:
        tags = [tag for tag in self._tags.values() if tag.user_id == user_id]
        tags.sort(key=lambda t: t.created_at, reverse=True)
        return tags[skip : skip + limit]

    def count_by_user(self, user_id: str) -> int:
        return sum(1 for tag in self._tags.values() if tag.user_id == user_id)

    def delete(self, tag_id: str) -> bool:
        if tag_id in self._tags:
            del self._tags[tag_id]
            return True
        return False
