from typing import List

from django.shortcuts import get_object_or_404
from ninja import Router
from ninja.pagination import paginate

from .auth import AuthBearer
from .models import Comment, Post
from .schemas import CommentCreate, CommentUpdate, CommentOut, ErrorMessage

router = Router()


@router.get("", response=List[CommentOut])
@paginate
def list_comments(request, post_id: int = None, parent_id: int = None):
    comments = Comment.objects.filter(is_deleted=False)
    
    if post_id:
        comments = comments.filter(post_id=post_id)
    if parent_id:
        comments = comments.filter(parent_id=parent_id)
    
    return comments.select_related('author', 'post', 'parent')


@router.get("/{comment_id}", response={200: CommentOut, 404: ErrorMessage})
def get_comment(request, comment_id: int):
    comment = get_object_or_404(Comment.objects.filter(is_deleted=False), id=comment_id)
    return 200, comment


@router.post("", response={201: CommentOut, 400: ErrorMessage}, auth=AuthBearer())
def create_comment(request, data: CommentCreate):
    try:
        # 验证帖子是否存在且未被删除
        post = Post.objects.get(id=data.post_id, is_deleted=False)
        
        # 如果有父评论，验证它是否存在且属于同一个帖子
        if data.parent_id:
            parent = Comment.objects.get(
                id=data.parent_id,
                post_id=data.post_id,
                is_deleted=False
            )
        else:
            parent = None
        
        # 创建评论
        comment = Comment.objects.create(
            content=data.content,
            post=post,
            parent=parent,
            author=request.auth
        )
        
        return 201, comment
        
    except Post.DoesNotExist:
        return 400, {"detail": "Post not found or has been deleted"}
    except Comment.DoesNotExist:
        return 400, {"detail": "Parent comment not found or has been deleted"}


@router.put("/{comment_id}", response={200: CommentOut, 400: ErrorMessage, 404: ErrorMessage}, auth=AuthBearer())
def update_comment(request, comment_id: int, data: CommentUpdate):
    try:
        comment = Comment.objects.get(
            id=comment_id,
            author=request.auth,
            is_deleted=False
        )
        
        comment.content = data.content
        comment.save()
        
        return 200, comment
        
    except Comment.DoesNotExist:
        return 404, {"detail": "Comment not found or you don't have permission to edit it"}


@router.delete("/{comment_id}", response={204: None, 404: ErrorMessage}, auth=AuthBearer())
def delete_comment(request, comment_id: int):
    comment = get_object_or_404(
        Comment,
        id=comment_id,
        author=request.auth,
        is_deleted=False
    )
    comment.delete()  # 这里会调用我们的软删除方法
    return 204, None
