package controller

import (
	"net/http"
	"strconv"

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

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

// loadArticlesData 加载文章列表数据
func (ctrl *SpaceController) loadArticlesData(c *gin.Context, data gin.H, uid uint, page, pageSize int) {
	posts, total, err := ctrl.spaceService.GetPostsByUser(uid, page, pageSize)
	if err != nil {
		posts = []model.Post{}
		total = 0
	}
	totalPages := common.PageCount(total, pageSize)
	data["Posts"] = posts
	data["Total"] = total
	data["Page"] = page
	data["TotalPages"] = totalPages
	data["PrevPage"] = max(1, page-1)
	data["NextPage"] = min(totalPages, page+1)
}

// loadFollowingData 加载关注列表数据
func (ctrl *SpaceController) loadFollowingData(c *gin.Context, data gin.H, targetUID, currentUID uint, page, pageSize int) {
	if ctrl.followSvc == nil {
		data["FollowingResult"] = &service.FollowListResult{Items: []model.UserFollow{}, Total: 0, Accessible: true}
		return
	}
	res, err := ctrl.followSvc.ListFollowing(targetUID, currentUID, page, pageSize)
	if err != nil || res == nil {
		res = &service.FollowListResult{Items: []model.UserFollow{}, Total: 0, Accessible: true}
	}
	data["FollowingResult"] = res
}

// loadFollowersData 加载粉丝列表数据
func (ctrl *SpaceController) loadFollowersData(c *gin.Context, data gin.H, targetUID, currentUID uint, page, pageSize int) {
	if ctrl.followSvc == nil {
		data["FollowersResult"] = &service.FollowListResult{Items: []model.UserFollow{}, Total: 0, Accessible: true}
		return
	}
	res, err := ctrl.followSvc.ListFollowers(targetUID, currentUID, page, pageSize)
	if err != nil || res == nil {
		res = &service.FollowListResult{Items: []model.UserFollow{}, Total: 0, Accessible: true}
	}
	data["FollowersResult"] = res
}

// loadCollectionsData 加载收藏夹数据
func (ctrl *SpaceController) loadCollectionsData(c *gin.Context, data gin.H, uid uint, page, pageSize int) {
	if ctrl.favoriteSvc == nil {
		data["FoldersResult"] = &service.FavoriteListResult{Folders: []model.Folder{}}
		return
	}

	// 收藏夹列表
	folders, err := ctrl.favoriteSvc.ListFolders(uid)
	if err != nil || folders == nil {
		folders = &service.FavoriteListResult{Folders: []model.Folder{}}
	}
	data["FoldersResult"] = folders

	// 默认展示第一个收藏夹的内容
	folderParam := c.DefaultQuery("folder", "")
	var activeFolderID uint
	if folderParam != "" {
		fid, parseErr := strconv.ParseUint(folderParam, 10, 64)
		if parseErr == nil {
			activeFolderID = uint(fid)
		}
	}
	if activeFolderID == 0 && len(folders.Folders) > 0 {
		activeFolderID = folders.Folders[0].ID
	}

	var folderItems *service.FolderItemsResult
	if activeFolderID > 0 {
		items, itemErr := ctrl.favoriteSvc.ListFolderItems(uid, activeFolderID, page, pageSize)
		if itemErr != nil || items == nil {
			folderItems = &service.FolderItemsResult{Items: []model.FolderItem{}, Total: 0}
		} else {
			folderItems = items
		}
	}
	if folderItems == nil {
		folderItems = &service.FolderItemsResult{Items: []model.FolderItem{}, Total: 0}
	}
	data["FolderItems"] = folderItems
	data["ActiveFolderID"] = activeFolderID

	// 找到当前激活的收藏夹对象传给模板
	var activeFolder *model.Folder
	for i := range folders.Folders {
		if folders.Folders[i].ID == activeFolderID {
			activeFolder = &folders.Folders[i]
			break
		}
	}
	data["ActiveFolder"] = activeFolder

	data["Page"] = page
	data["TotalPages"] = folderItems.TotalPages
	data["PrevPage"] = max(1, page-1)
	data["NextPage"] = min(folderItems.TotalPages, page+1)
}

// UpdatePrivacy PUT /api/space/privacy — 更新隐私设置
func (ctrl *SpaceController) UpdatePrivacy(c *gin.Context) {
	uid, _, ok := common.GetGinUser(c)
	if !ok {
		common.Error(c, http.StatusUnauthorized, "请先登录")
		return
	}

	var req struct {
		Field string `json:"field"`
		Value bool   `json:"value"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, http.StatusBadRequest, "参数错误")
		return
	}

	// 支持的字段映射（仅处理已实现的字段）
	allowedFields := map[string]string{
		"follow_list":   "follow_list_public",
		"follower_list": "follower_list_public",
	}

	column, ok := allowedFields[req.Field]
	if !ok {
		common.OkMessage(c, "已保存") // 未实现字段直接返回成功，前端不感知
		return
	}

	user, err := ctrl.spaceService.GetSpaceUser(uid)
	if err != nil || user == nil {
		common.Error(c, http.StatusNotFound, "用户不存在")
		return
	}

	switch column {
	case "follow_list_public":
		user.FollowListPublic = req.Value
	case "follower_list_public":
		user.FollowerListPublic = req.Value
	}

	if err := ctrl.spaceService.UpdateUser(user); err != nil {
		common.Error(c, http.StatusInternalServerError, "保存失败")
		return
	}

	common.OkMessage(c, "隐私设置已更新")
}
