package chat

import (
	"hfb_sys/backend/pkg/response"

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

func (h *Handler) List(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	h.list(c, Principal{Type: "user", ID: userID})
}

func (h *Handler) UnreadCount(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	result, err := h.service.CountUnreadMessages(c.Request.Context(), Principal{Type: "user", ID: userID})
	if err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, result)
}

func (h *Handler) Detail(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	h.detail(c, Principal{Type: "user", ID: userID})
}

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

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

func (h *Handler) Messages(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	h.messages(c, Principal{Type: "user", ID: userID})
}

func (h *Handler) Send(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	h.send(c, Principal{Type: "user", ID: userID})
}

func (h *Handler) MarkRead(c *gin.Context) {
	userID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	h.markRead(c, Principal{Type: "user", ID: userID})
}
