package app

import (
	"net/http"
	"strconv"

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

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

type drawLogItem struct {
	ID           int64 `json:"id"`
	UserID       int64 `json:"user_id"`
	IssueID      int64 `json:"issue_id"`
	OrderID      int64 `json:"order_id"`
	RewardID     int64 `json:"reward_id"`
	IsWinner     int32 `json:"is_winner"`
	Level        int32 `json:"level"`
	CurrentLevel int32 `json:"current_level"`
}

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

// ListDrawLogs 抽奖记录列表
// @Summary 抽奖记录列表
// @Description 查看指定活动期数的抽奖记录，支持分页
// @Tags APP端.活动
// @Accept json
// @Produce json
// @Param activity_id path integer true "活动ID"
// @Param issue_id path integer true "期ID"
// @Param page query int true "页码" default(1)
// @Param page_size query int true "每页数量，最多100" default(20)
// @Success 200 {object} listDrawLogsResponse
// @Failure 400 {object} code.Failure
// @Router /api/app/activities/{activity_id}/issues/{issue_id}/draw_logs [get]
func (h *handler) ListDrawLogs() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(listDrawLogsRequest)
		res := new(listDrawLogsResponse)
		if err := ctx.ShouldBindForm(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}
		issueID, err := strconv.ParseInt(ctx.Param("issue_id"), 10, 64)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "未传递期ID"))
			return
		}
		items, total, err := h.activity.ListDrawLogs(ctx.RequestContext(), issueID, req.Page, req.PageSize)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ListDrawLogsError, err.Error()))
			return
		}
		res.Page = req.Page
		res.PageSize = req.PageSize
		res.Total = total
		res.List = make([]drawLogItem, len(items))
		for i, v := range items {
			res.List[i] = drawLogItem{
				ID:           v.ID,
				UserID:       v.UserID,
				IssueID:      v.IssueID,
				OrderID:      v.OrderID,
				RewardID:     v.RewardID,
				IsWinner:     v.IsWinner,
				Level:        v.Level,
				CurrentLevel: v.CurrentLevel,
			}
		}
		ctx.Payload(res)
	}
}
