package app

import (
	"net/http"

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

type cancelShippingRequest struct {
	InventoryID int64  `json:"inventory_id"` // 单个资产ID（与batch_no二选一）
	BatchNo     string `json:"batch_no"`     // 批次号（与inventory_id二选一，取消整批）
}

type cancelShippingResponse struct {
	CancelledCount int64 `json:"cancelled_count"` // 成功取消的数量
}

// CancelShipping 取消发货申请
// @Summary 取消发货申请
// @Description 取消已提交但未发货的申请；恢复库存状态。支持按单个资产ID取消或按批次号批量取消
// @Tags APP端.用户
// @Accept json
// @Produce json
// @Security LoginVerifyToken
// @Param user_id path integer true "用户ID"
// @Param RequestBody body cancelShippingRequest true "请求参数：资产ID或批次号（二选一）"
// @Success 200 {object} cancelShippingResponse "成功"
// @Failure 400 {object} code.Failure "参数错误/记录不存在/已处理"
// @Router /api/app/users/{user_id}/inventory/cancel-shipping [post]
func (h *handler) CancelShipping() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(cancelShippingRequest)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "参数错误"))
			return
		}
		// 必须提供 inventory_id 或 batch_no 其中之一
		if req.InventoryID == 0 && req.BatchNo == "" {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "请提供inventory_id或batch_no"))
			return
		}
		userID := int64(ctx.SessionUserInfo().Id)
		count, err := h.user.CancelShipping(ctx.RequestContext(), userID, req.InventoryID, req.BatchNo)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10024, err.Error()))
			return
		}
		ctx.Payload(&cancelShippingResponse{CancelledCount: count})
	}
}
