package app

import (
	"net/http"
	"strconv"

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

type listIssuesRequest struct {
	Page     int `form:"page"`
	PageSize int `form:"page_size"`
}

type issueItem struct {
	ID                     int64  `json:"id"`
	IssueNumber            string `json:"issue_number"`
	Status                 int32  `json:"status"`
	Sort                   int32  `json:"sort"`
	TotalPrizeQuantity     int64  `json:"total_prize_quantity"`
	RemainingPrizeQuantity int64  `json:"remaining_prize_quantity"`
}

type listIssuesResponse struct {
	Page     int         `json:"page"`
	PageSize int         `json:"page_size"`
	Total    int64       `json:"total"`
	List     []issueItem `json:"list"`
}

// ListActivityIssues 活动期列表
// @Summary 活动期列表
// @Description 获取指定活动的期列表，支持分页
// @Tags APP端.活动
// @Accept json
// @Produce json
// @Param activity_id path integer true "活动ID"
// @Param page query int true "页码" default(1)
// @Param page_size query int true "每页数量，最多100" default(20)
// @Success 200 {object} listIssuesResponse
// @Failure 400 {object} code.Failure
// @Router /api/app/activities/{activity_id}/issues [get]
func (h *handler) ListActivityIssues() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(listIssuesRequest)
		res := new(listIssuesResponse)
		if err := ctx.ShouldBindForm(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}
		activityID, err := strconv.ParseInt(ctx.Param("activity_id"), 10, 64)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "未传递活动ID"))
			return
		}
		activityItem, err := h.readDB.Activities.WithContext(ctx.RequestContext()).Where(h.readDB.Activities.ID.Eq(activityID)).First()
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.GetActivityError, "获取活动信息失败: "+err.Error()))
			return
		}
		items, total, err := h.activity.ListIssues(ctx.RequestContext(), activityID, req.Page, req.PageSize)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ListActivityIssuesError, err.Error()))
			return
		}
		res.Page = req.Page
		res.PageSize = req.PageSize
		res.Total = total
		res.List = make([]issueItem, len(items))
		for i, v := range items {
			it := issueItem{ID: v.ID, IssueNumber: v.IssueNumber, Status: v.Status, Sort: v.Sort}
			if activityItem.ActivityCategoryID == 1 {
				rewards, _ := h.readDB.ActivityRewardSettings.WithContext(ctx.RequestContext()).ReadDB().Where(h.readDB.ActivityRewardSettings.IssueID.Eq(v.ID)).Find()
				// 一番赏：每种奖品 = 1个格位
				totalQty := int64(len(rewards))
				// 查询已占用格位数
				var claimedCnt int64
				_ = h.repo.GetDbR().Raw("SELECT COUNT(*) FROM issue_position_claims WHERE issue_id = ?", v.ID).Scan(&claimedCnt).Error
				remainQty := totalQty - claimedCnt
				if remainQty < 0 {
					remainQty = 0
				}
				it.TotalPrizeQuantity = totalQty
				it.RemainingPrizeQuantity = remainQty
			}
			res.List[i] = it
		}
		ctx.Payload(res)
	}
}
