package controller

import (
	"net/http"
	"strconv"

	"metazone.cc/metalab/internal/common"

	"github.com/gin-gonic/gin"
)

// CreateRoot POST /api/posts/:id/comments
func (ctrl *CommentController) CreateRoot(c *gin.Context) {
	uid, _, ok := common.GetGinUser(c)
	if !ok {
		common.Error(c, http.StatusUnauthorized, "请先登录")
		return
	}

	postID, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil {
		common.Error(c, http.StatusBadRequest, "无效的文章ID")
		return
	}

	var req struct {
		Body string `json:"body" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, http.StatusBadRequest, "请输入评论内容")
		return
	}

	comment, err := ctrl.commentService.CreateRoot(uid, uint(postID), req.Body)
	if err != nil {
		common.Error(c, http.StatusBadRequest, err.Error())
		return
	}

	common.Ok(c, comment)
}

// CreateReply POST /api/comments/:id/reply
func (ctrl *CommentController) CreateReply(c *gin.Context) {
	uid, _, ok := common.GetGinUser(c)
	if !ok {
		common.Error(c, http.StatusUnauthorized, "请先登录")
		return
	}

	parentID, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil {
		common.Error(c, http.StatusBadRequest, "无效的评论ID")
		return
	}

	var req struct {
		Body string `json:"body" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, http.StatusBadRequest, "请输入回复内容")
		return
	}

	reply, err := ctrl.commentService.CreateReply(uid, uint(parentID), req.Body)
	if err != nil {
		common.Error(c, http.StatusBadRequest, err.Error())
		return
	}

	common.Ok(c, reply)
}
