package controller

import (
	"net/http"
	"strconv"

	"metazone.cc/metalab/internal/common"

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

// SpaceController 用户空间控制器
type SpaceController struct {
	spaceService spaceUseCase
}

// NewSpaceController 构造函数
func NewSpaceController(spaceService spaceUseCase) *SpaceController {
	return &SpaceController{spaceService: spaceService}
}

// MySpace 自己的空间（/space）— 需登录，重定向到 /space/{uid}
func (ctrl *SpaceController) MySpace(c *gin.Context) {
	uid, _, ok := common.GetGinUser(c)
	if !ok {
		c.Redirect(http.StatusFound, "/auth/login")
		return
	}
	c.Redirect(http.StatusFound, "/space/"+strconv.FormatUint(uint64(uid), 10))
}

// ShowSpace 查看他人或自己的空间（/space/:uid）— 无需认证
func (ctrl *SpaceController) ShowSpace(c *gin.Context) {
	uidStr := c.Param("uid")
	uid, err := strconv.ParseUint(uidStr, 10, 64)
	if err != nil {
		c.HTML(http.StatusNotFound, "space/index.html", common.BuildPageData(c, gin.H{
			"Title":    "用户不存在",
			"Error":    "用户不存在",
			"ExtraCSS": "/static/css/space.css",
		}))
		return
	}

	spaceUser, err := ctrl.spaceService.GetSpaceUser(uint(uid))
	if err != nil || spaceUser == nil {
		c.HTML(http.StatusNotFound, "space/index.html", common.BuildPageData(c, gin.H{
			"Title":    "用户不存在",
			"Error":    "用户不存在",
			"ExtraCSS": "/static/css/space.css",
		}))
		return
	}

	// 分页
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	if page < 1 {
		page = 1
	}
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))
	if pageSize < 1 || pageSize > 50 {
		pageSize = 10
	}

	posts, total, err := ctrl.spaceService.GetPostsByUser(uint(uid), page, pageSize)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "space/index.html", common.BuildPageData(c, gin.H{
			"Title":    "加载失败",
			"Error":    "加载帖子失败，请稍后重试",
			"ExtraCSS": "/static/css/space.css",
		}))
		return
	}

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

	// 检查是否是自己的空间
	isOwnSpace := false
	if currentUID, _, ok := common.GetGinUser(c); ok {
		isOwnSpace = currentUID == uint(uid)
	}

	c.HTML(http.StatusOK, "space/index.html", common.BuildPageData(c, gin.H{
		"Title":      spaceUser.Username + " 的空间",
		"SpaceUser":  spaceUser,
		"Posts":      posts,
		"Total":      total,
		"Page":       page,
		"TotalPages": totalPages,
		"PrevPage":   prevPage,
		"NextPage":   nextPage,
		"IsOwnSpace": isOwnSpace,
		"ExtraCSS":   "/static/css/space.css",
	}))
}
