package admin

import (
	"net/http"
	"strconv"

	"metazone.cc/metalab/internal/common"

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

// AdminPostController 管理后台帖子控制器
type AdminPostController struct {
	postService adminPostUseCase
}

// NewAdminPostController 构造函数
func NewAdminPostController(ps adminPostUseCase) *AdminPostController {
	return &AdminPostController{postService: ps}
}

// PostsPage 管理后台帖子列表页
func (ctrl *AdminPostController) PostsPage(c *gin.Context) {
	keyword := c.Query("keyword")
	status := c.Query("status")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))

	posts, total, err := ctrl.postService.ListAdmin(keyword, status, page, pageSize)
	if err != nil {
		c.HTML(http.StatusOK, "admin/posts/index.html", common.BuildAdminPageData(c, gin.H{
			"Title": "内容管理",
			"Error": "加载帖子列表失败",
		}))
		return
	}

	totalPages := common.PageCount(total, pageSize)
	prevPage := page - 1
	if prevPage < 1 {
		prevPage = 1
	}
	nextPage := page + 1
	if nextPage > totalPages {
		nextPage = totalPages
	}

	c.HTML(http.StatusOK, "admin/posts/index.html", common.BuildAdminPageData(c, gin.H{
		"Title":       "内容管理",
		"Posts":       posts,
		"Total":       total,
		"Page":        page,
		"TotalPages":  totalPages,
		"PrevPage":    prevPage,
		"NextPage":    nextPage,
		"Keyword":     keyword,
		"Status":      status,
		"StatusNames": common.PostStatusDisplayNames,
		"ExtraCSS":    "/admin/static/css/posts.css",
	}))
}
