package admin

import (
	"net/http"
	"strconv"

	"metazone.cc/metalab/internal/common"
	"metazone.cc/metalab/internal/model"

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

// AdminCommentController 后台评论管理
type AdminCommentController struct {
	commentService adminCommentUseCase
}

// NewAdminCommentController 构造函数
func NewAdminCommentController(cs adminCommentUseCase) *AdminCommentController {
	return &AdminCommentController{commentService: cs}
}

// CommentsPage SSR 页面
func (ctrl *AdminCommentController) CommentsPage(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/comments/index.html", common.BuildAdminPageData(c, gin.H{
		"Title": "评论管理",
	}))
}

// ListComments API 列表
func (ctrl *AdminCommentController) ListComments(c *gin.Context) {
	keyword := c.Query("keyword")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))

	comments, total, err := ctrl.commentService.ListAllComments(keyword, false, page, pageSize)
	if err != nil {
		common.Error(c, http.StatusInternalServerError, "获取评论列表失败")
		return
	}
	if comments == nil {
		comments = []model.AdminCommentRow{}
	}

	common.Ok(c, gin.H{
		"items":       comments,
		"total":       total,
		"page":        page,
		"total_pages": common.PageCount(total, pageSize),
	})
}

// Delete 软删除评论
func (ctrl *AdminCommentController) Delete(c *gin.Context) {
	commentID, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil {
		common.Error(c, http.StatusBadRequest, "无效的评论ID")
		return
	}
	if err := ctrl.commentService.Delete(uint(commentID), 0, true); err != nil {
		common.Error(c, http.StatusBadRequest, err.Error())
		return
	}
	common.OkMessage(c, "删除成功")
}
