"""标签 CRUD 路由。"""

import logging
from typing import Any

from app.auth import AuthenticatedUser, get_current_user
from app.dependencies import get_tag_repository
from app.schemas.tag import (
    CreateTagRequest,
    ListTagsResponse,
    TagResponse,
)
from fastapi import APIRouter, Depends, HTTPException

from packages.domain import Tag

logger = logging.getLogger(__name__)

router = APIRouter()


@router.get("", response_model=ListTagsResponse)
def list_tags(
    skip: int = 0,
    limit: int = 100,
    authenticated_user: AuthenticatedUser = Depends(get_current_user),
    tag_repository: Any = Depends(get_tag_repository),
) -> ListTagsResponse:
    """列出当前用户的标签。"""
    user_id = authenticated_user.user.id
    items = tag_repository.list_by_user(user_id, skip=skip, limit=limit)
    total = tag_repository.count_by_user(user_id)
    return ListTagsResponse(
        items=[TagResponse(id=t.id, name=t.name, created_at=t.created_at) for t in items],
        total=total,
    )


@router.post("", response_model=TagResponse, status_code=201)
def create_tag(
    request: CreateTagRequest,
    authenticated_user: AuthenticatedUser = Depends(get_current_user),
    tag_repository: Any = Depends(get_tag_repository),
) -> TagResponse:
    """创建标签（同用户同名去重，返回 409）。"""
    user_id = authenticated_user.user.id
    existing = tag_repository.find_by_name(user_id, request.name)
    if existing:
        raise HTTPException(status_code=409, detail="标签名称已存在")
    tag = Tag.create(user_id=user_id, name=request.name)
    created = tag_repository.create(tag)
    return TagResponse(id=created.id, name=created.name, created_at=created.created_at)


@router.delete("/{tag_id}", status_code=204)
def delete_tag(
    tag_id: str,
    authenticated_user: AuthenticatedUser = Depends(get_current_user),
    tag_repository: Any = Depends(get_tag_repository),
) -> None:
    """删除标签（同时清理素材关联）。"""
    tag = tag_repository.get(tag_id)
    if tag is None:
        raise HTTPException(status_code=404, detail="标签不存在")
    if tag.user_id != authenticated_user.user.id:
        raise HTTPException(status_code=403, detail="无权删除该标签")
    tag_repository.delete(tag_id)
