package app

import (
	"net/http"

	"bindbox-game/internal/code"
	"bindbox-game/internal/pkg/core"
	"bindbox-game/internal/pkg/validation"
	"bindbox-game/internal/service/user"
	"strconv"
	"time"
)

type listOrdersRequest struct {
	Page       int    `form:"page"`
	PageSize   int    `form:"page_size"`
	Status     int32  `form:"status"`
	IsConsumed *int32 `form:"is_consumed"`
}
type listOrdersResponse struct {
	Page     int                    `json:"page"`
	PageSize int                    `json:"page_size"`
	Total    int64                  `json:"total"`
	List     []*user.OrderWithItems `json:"list"`
}

// ListUserOrders 查看用户订单记录
// @Summary 查看用户订单记录
// @Description 查看用户抽奖来源订单记录
// @Tags APP端.用户
// @Accept json
// @Produce json
// @Param user_id path integer true "用户ID"
// @Security LoginVerifyToken
// @Param page query int true "页码" default(1)
// @Param page_size query int true "每页数量，最多100" default(20)
// @Param status query int false "订单状态：1待支付 2已支付 3已取消 4已退款"
// @Param is_consumed query int false "是否已消耗/履约：0否 1是"
// @Success 200 {object} listOrdersResponse
// @Failure 400 {object} code.Failure
// @Router /api/app/users/{user_id}/orders [get]
func (h *handler) ListUserOrders() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(listOrdersRequest)
		rsp := new(listOrdersResponse)
		if err := ctx.ShouldBindForm(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}
		userID := int64(ctx.SessionUserInfo().Id)

		items, total, err := h.user.ListOrdersWithItems(ctx.RequestContext(), userID, req.Status, req.IsConsumed, req.Page, req.PageSize)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10002, err.Error()))
			return
		}
		rsp.Page = req.Page
		rsp.PageSize = req.PageSize
		rsp.Total = total
		rsp.List = items
		ctx.Payload(rsp)
	}
}

// GetOrderDetail 获取订单详情
// @Summary 获取订单详情
// @Description 获取指定订单的详细信息
// @Tags APP端.用户
// @Accept json
// @Produce json
// @Security LoginVerifyToken
// @Param order_id path int true "订单ID"
// @Success 200 {object} user.OrderWithItems
// @Failure 400 {object} code.Failure
// @Router /api/app/orders/{order_id} [get]
func (h *handler) GetOrderDetail() core.HandlerFunc {
	return func(ctx core.Context) {
		orderIDStr := ctx.Param("order_id")
		orderID, err := strconv.ParseInt(orderIDStr, 10, 64)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "订单ID格式错误"))
			return
		}
		userID := int64(ctx.SessionUserInfo().Id)
		order, err := h.user.GetOrderWithItems(ctx.RequestContext(), userID, orderID)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10003, err.Error()))
			return
		}
		if order == nil {
			ctx.AbortWithError(core.Error(http.StatusNotFound, 10004, "订单不存在"))
			return
		}
		ctx.Payload(order)
	}
}

type cancelOrderRequest struct {
	Reason string `json:"reason"`
}

type cancelOrderResponse struct {
	OrderID     int64      `json:"order_id"`
	OrderNo     string     `json:"order_no"`
	Status      int32      `json:"status"`
	CancelledAt *time.Time `json:"cancelled_at"`
}

// CancelOrder 取消订单
// @Summary 取消订单
// @Description 取消指定订单（仅限待付款状态）
// @Tags APP端.用户
// @Accept json
// @Produce json
// @Security LoginVerifyToken
// @Param order_id path int true "订单ID"
// @Param body body cancelOrderRequest false "取消原因"
// @Success 200 {object} cancelOrderResponse
// @Failure 400 {object} code.Failure
// @Router /api/app/orders/{order_id}/cancel [post]
func (h *handler) CancelOrder() core.HandlerFunc {
	return func(ctx core.Context) {
		orderIDStr := ctx.Param("order_id")
		orderID, err := strconv.ParseInt(orderIDStr, 10, 64)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "订单ID格式错误"))
			return
		}

		req := new(cancelOrderRequest)
		_ = ctx.ShouldBindJSON(req) // Body is optional

		userID := int64(ctx.SessionUserInfo().Id)
		order, err := h.user.CancelOrder(ctx.RequestContext(), userID, orderID, req.Reason)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10005, err.Error()))
			return
		}

		ctx.Payload(&cancelOrderResponse{
			OrderID:     order.ID,
			OrderNo:     order.OrderNo,
			Status:      order.Status,
			CancelledAt: &order.CancelledAt,
		})
	}
}
