package listing

import (
	"hfb_sys/backend/pkg/response"
	"strings"

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

func (h *Handler) Create(c *gin.Context) {
	ownerID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	var req CreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, listingBindErrorMessage(err))
		return
	}
	item, err := h.service.Create(c.Request.Context(), ownerID, req)
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.Created(c, item)
}

func (h *Handler) Update(c *gin.Context) {
	ownerID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	id, ok := parseID(c)
	if !ok {
		return
	}
	var req UpdateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, listingBindErrorMessage(err))
		return
	}
	item, err := h.service.Update(c.Request.Context(), ownerID, id, req)
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, item)
}

func listingBindErrorMessage(err error) string {
	if err == nil {
		return "发布信息不完整"
	}
	message := strings.ToLower(err.Error())
	if strings.Contains(message, "hafcoinamount") || strings.Contains(message, "haf_coin_amount") {
		return "哈夫币数量格式不正确，请重新填写哈夫币/M后再提交"
	}
	return "发布信息不完整"
}

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

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

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

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