package app

import (
	"encoding/json"
	"net/http"
	"strconv"

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

type rewardItem struct {
	ProductID    int64  `json:"product_id"`
	Name         string `json:"name"`
	Weight       int32  `json:"weight"`
	Quantity     int64  `json:"quantity"`
	OriginalQty  int64  `json:"original_qty"`
	Level        int32  `json:"level"`
	Sort         int32  `json:"sort"`
	IsBoss       int32  `json:"is_boss"`
	ProductImage string `json:"product_image"`
}

type listRewardsResponse struct {
	List []rewardItem `json:"list"`
}

// ListIssueRewards 奖励配置列表
// @Summary 奖励配置列表
// @Description 获取指定期的奖励配置列表
// @Tags APP端.活动
// @Accept json
// @Produce json
// @Param activity_id path integer true "活动ID"
// @Param issue_id path integer true "期ID"
// @Success 200 {object} listRewardsResponse
// @Failure 400 {object} code.Failure
// @Router /api/app/activities/{activity_id}/issues/{issue_id}/rewards [get]
func (h *handler) ListIssueRewards() core.HandlerFunc {
	return func(ctx core.Context) {
		issueIDStr := ctx.Param("issue_id")
		if issueIDStr == "" {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "未传递期ID"))
			return
		}
		if _, err := strconv.ParseInt(issueIDStr, 10, 64); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}
		issueID, _ := strconv.ParseInt(issueIDStr, 10, 64)
		items, err := h.activity.ListIssueRewards(ctx.RequestContext(), issueID)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ListIssueRewardsError, err.Error()))
			return
		}
		pidSet := make(map[int64]struct{})
		for _, v := range items {
			if v.ProductID > 0 {
				pidSet[v.ProductID] = struct{}{}
			}
		}
		imageMap := make(map[int64]string)
		nameMap := make(map[int64]string)
		if len(pidSet) > 0 {
			ids := make([]int64, 0, len(pidSet))
			for id := range pidSet {
				ids = append(ids, id)
			}
			pros, err := h.readDB.Products.WithContext(ctx.RequestContext()).ReadDB().Where(h.readDB.Products.ID.In(ids...)).Find()
			if err == nil {
				for _, p := range pros {
					first := ""
					if p.ImagesJSON != "" {
						var arr []string
						_ = json.Unmarshal([]byte(p.ImagesJSON), &arr)
						if len(arr) > 0 {
							first = arr[0]
						}
					}
					imageMap[p.ID] = first
					nameMap[p.ID] = p.Name
				}
			}
		}
		res := new(listRewardsResponse)
		res.List = make([]rewardItem, len(items))
		for i, v := range items {
			// 优先使用配置的名称，若为空则回退为商品名称
			nameVal := v.Name
			if nameVal == "" {
				if nm, ok := nameMap[v.ProductID]; ok {
					nameVal = nm
				}
			}
			res.List[i] = rewardItem{
				ProductID:    v.ProductID,
				Name:         nameVal,
				Weight:       v.Weight,
				Quantity:     v.Quantity,
				OriginalQty:  v.OriginalQty,
				Level:        v.Level,
				Sort:         v.Sort,
				IsBoss:       v.IsBoss,
				ProductImage: imageMap[v.ProductID],
			}
		}
		ctx.Payload(res)
	}
}
