package controller

import (
	"net/http"
	"strconv"

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

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

// MessagesPage 消息中心页面（需登录，noindex）
func (mc *MessageController) MessagesPage(c *gin.Context) {
	uidVal, exists := c.Get("uid")
	if !exists {
		common.RedirectToLogin(c)
		return
	}
	uid := uidVal.(uint)

	// 从 query 取分页参数
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	if page < 1 {
		page = 1
	}
	pageSize := 20

	result, err := mc.notifService.List(uid, page, pageSize)
	if err != nil {
		result = &model.NotificationListResult{Items: []model.Notification{}, Total: 0, Page: 1}
	}

	totalPages := result.TotalPages
	if totalPages == 0 && result.Total > 0 {
		totalPages = int((result.Total + int64(pageSize) - 1) / int64(pageSize))
	}

	c.HTML(http.StatusOK, "messages/index.html", common.BuildPageData(c, gin.H{
		"Title":           "消息中心",
		"ExtraCSS":        "/static/css/messages.css",
		"Messages":        result.Items,
		"Total":           result.Total,
		"Page":            result.Page,
		"TotalPages":      totalPages,
		"PrevPage":        result.Page - 1,
		"NextPage":        result.Page + 1,
		"HasPrev":         result.Page > 1,
		"HasNext":         result.Page < totalPages,
		"UnreadCount":     result.Unread,
		"NotifyTypeNames": model.NotifyTypeNames,
		"AuditTypeNames":  model.AuditTypeNames,
	}))
}
