package app

import (
	"bindbox-game/internal/code"
	"bindbox-game/internal/pkg/core"
	"bindbox-game/internal/pkg/validation"
	usersvc "bindbox-game/internal/service/user"
	"net/http"
	"strconv"
)

type redeemProductRequest struct {
	ProductID int64 `json:"product_id"`
	Quantity  int   `json:"quantity"`
}

type redeemProductResponse struct {
	Success      bool    `json:"success"`
	LedgerID     int64   `json:"ledger_id"`
	OrderID      int64   `json:"order_id"`
	InventoryIDs []int64 `json:"inventory_ids"`
	Message      string  `json:"message"`
}

// RedeemPointsToProduct 积分兑换商品
// @Summary 积分兑换商品
// @Description 使用积分按比率1积分=1元兑换商品，生成系统发放订单与用户资产
// @Tags APP端.积分
// @Accept json
// @Produce json
// @Security LoginVerifyToken
// @Param RequestBody body redeemProductRequest true "请求参数"
// @Success 200 {object} redeemProductResponse
// @Failure 400 {object} code.Failure
// @Router /api/app/users/{user_id}/points/redeem-product [post]
// RedeemPointsToProduct 使用积分兑换商品处理器
// 功能：按商品价格扣减积分并生成系统发放订单与用户资产
// 参数：无（通过上下文获取 user_id，body 解析 product_id/quantity）
// 返回：core.HandlerFunc 处理 POST /api/app/users/{user_id}/points/redeem-product
func (h *handler) RedeemPointsToProduct() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(redeemProductRequest)
		rsp := new(redeemProductResponse)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}
		if req.Quantity <= 0 {
			req.Quantity = 1
		}
		userID := int64(ctx.SessionUserInfo().Id)
		prod, err := h.readDB.Products.WithContext(ctx.RequestContext()).Where(h.readDB.Products.ID.Eq(req.ProductID)).First()
		if err != nil || prod == nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 150101, "product not found"))
			return
		}
		// 检查商品库存
		if prod.Stock <= 0 {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 150105, "商品库存不足，请联系客服处理"))
			return
		}
		// prod.Price 是商品价格（分），直接用于扣除
		// 例如：30 元商品 = 3000 分
		needCents := prod.Price * int64(req.Quantity)
		if needCents <= 0 {
			needCents = 1
		}
		ledgerID, err := h.user.ConsumePointsFor(ctx.RequestContext(), userID, needCents, "products", strconv.FormatInt(req.ProductID, 10), "redeem product", "redeem_product")
		if err != nil {
			errMsg := err.Error()
			if errMsg == "insufficient_points" {
				errMsg = "积分不足，无法完成兑换"
			}
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 150102, errMsg))
			return
		}

		// Mall Direct Purchase (SourceType=1)
		sourceType := int32(1)
		resp, err := h.user.GrantReward(ctx.RequestContext(), userID, usersvc.GrantRewardRequest{
			ProductID:    req.ProductID,
			Quantity:     req.Quantity,
			Remark:       prod.Name,
			PointsAmount: needCents,
			SourceType:   &sourceType,
		})
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 150103, err.Error()))
			return
		}
		rsp.Success = true
		rsp.LedgerID = ledgerID
		rsp.OrderID = resp.OrderID
		rsp.InventoryIDs = resp.InventoryIDs
		rsp.Message = "ok"
		ctx.Payload(rsp)
	}
}
