from django.shortcuts import get_object_or_404
from ninja import Router

from .auth import AuthBearer
from .models import Like, Post, Comment
from .schemas import LikeCreate, ErrorMessage

router = Router()


@router.post("", response={201: None, 400: ErrorMessage}, auth=AuthBearer())
def create_like(request, data: LikeCreate):
    try:
        # 验证请求数据
        if (data.post_id is None and data.comment_id is None) or \
           (data.post_id is not None and data.comment_id is not None):
            return 400, {"detail": "Must provide either post_id or comment_id, not both or neither"}
        
        # 处理帖子点赞
        if data.post_id:
            post = Post.objects.get(id=data.post_id, is_deleted=False)
            # 检查是否已经点赞
            if Like.objects.filter(user=request.auth, post=post).exists():
                return 400, {"detail": "You have already liked this post"}
            Like.objects.create(user=request.auth, post=post)
            
        # 处理评论点赞
        else:
            comment = Comment.objects.get(id=data.comment_id, is_deleted=False)
            # 检查是否已经点赞
            if Like.objects.filter(user=request.auth, comment=comment).exists():
                return 400, {"detail": "You have already liked this comment"}
            Like.objects.create(user=request.auth, comment=comment)
            
        return 201, None
        
    except (Post.DoesNotExist, Comment.DoesNotExist):
        return 400, {"detail": "Post or comment not found or has been deleted"}


@router.delete("/post/{post_id}", response={204: None, 404: ErrorMessage}, auth=AuthBearer())
def delete_post_like(request, post_id: int):
    like = get_object_or_404(
        Like,
        post_id=post_id,
        user=request.auth
    )
    like.delete()
    return 204, None


@router.delete("/comment/{comment_id}", response={204: None, 404: ErrorMessage}, auth=AuthBearer())
def delete_comment_like(request, comment_id: int):
    like = get_object_or_404(
        Like,
        comment_id=comment_id,
        user=request.auth
    )
    like.delete()
    return 204, None
