package order

import (
	"hfb_sys/backend/pkg/response"

	"github.com/gin-gonic/gin"
)

func (h *Handler) Create(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	var req CreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "订单信息不完整")
		return
	}
	item, err := h.service.Create(c.Request.Context(), userID, req)
	if err != nil {
		writeOrderError(c, err)
		return
	}
	response.Created(c, item)
}

func (h *Handler) List(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	items, err := h.service.ListForUser(c.Request.Context(), userID)
	if err != nil {
		writeOrderError(c, err)
		return
	}
	response.OK(c, gin.H{"items": items})
}

func (h *Handler) Detail(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	id, ok := parseID(c)
	if !ok {
		return
	}
	item, err := h.service.FindForUser(c.Request.Context(), userID, id)
	if err != nil {
		writeOrderError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) Cancel(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	id, ok := parseID(c)
	if !ok {
		return
	}
	if err := h.service.Cancel(c.Request.Context(), userID, id); err != nil {
		writeOrderError(c, err)
		return
	}
	response.OK(c, gin.H{"cancelled": true})
}

func (h *Handler) Pay(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	id, ok := parseID(c)
	if !ok {
		return
	}
	if err := h.service.Pay(c.Request.Context(), userID, id); err != nil {
		writeOrderError(c, err)
		return
	}
	response.OK(c, gin.H{"paid": true})
}
