package admin

import (
	"net/http"
	"strconv"

	"bindbox-game/internal/code"
	"bindbox-game/internal/pkg/core"
	"bindbox-game/internal/pkg/validation"
)

type listGuildMembersRequest struct {
	Page     int `form:"page"`
	PageSize int `form:"page_size"`
}
type memberItem struct {
	ID        int64  `json:"id"`
	UserID    int64  `json:"user_id"`
	Role      string `json:"role"`
	StartTime string `json:"start_time"`
}
type listGuildMembersResponse struct {
	Page     int          `json:"page"`
	PageSize int          `json:"page_size"`
	Total    int64        `json:"total"`
	List     []memberItem `json:"list"`
}

// ListGuildMembers 查看工会成员
// @Summary 查看工会成员
// @Description 查看指定工会的成员列表
// @Tags 管理端.工会
// @Accept json
// @Produce json
// @Param guild_id path integer true "工会ID"
// @Param page query int true "页码" default(1)
// @Param page_size query int true "每页数量，最多100" default(20)
// @Success 200 {object} listGuildMembersResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin/guilds/{guild_id}/members [get]
// @Security LoginVerifyToken
func (h *handler) ListGuildMembers() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(listGuildMembersRequest)
		res := new(listGuildMembersResponse)
		if err := ctx.ShouldBindForm(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}
		if ctx.SessionUserInfo().IsSuper != 1 {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ListGuildMembersError, "禁止操作"))
			return
		}
		id, err := strconv.ParseInt(ctx.Param("guild_id"), 10, 64)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "未传递工会ID"))
			return
		}
		items, total, err := h.guild.ListMembers(ctx.RequestContext(), id, req.Page, req.PageSize)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ListGuildMembersError, err.Error()))
			return
		}
		res.Page = req.Page
		res.PageSize = req.PageSize
		res.Total = total
		res.List = make([]memberItem, len(items))
		for i, v := range items {
			res.List[i] = memberItem{ID: v.ID, UserID: v.UserID, Role: v.Role, StartTime: v.StartTime.Format("2006-01-02 15:04:05")}
		}
		ctx.Payload(res)
	}
}
