package chat

import (
	"hfb_sys/backend/pkg/response"

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

func (h *Handler) list(c *gin.Context, principal Principal) {
	page, pageSize := parsePagination(c)
	result, err := h.service.ListConversations(c.Request.Context(), principal, page, pageSize)
	if err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, result)
}

func (h *Handler) detail(c *gin.Context, principal Principal) {
	id, ok := parseID(c, "id")
	if !ok {
		return
	}
	item, err := h.service.FindConversation(c.Request.Context(), principal, id)
	if err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) messages(c *gin.Context, principal Principal) {
	id, ok := parseID(c, "id")
	if !ok {
		return
	}
	page, pageSize := parsePagination(c)
	result, err := h.service.Messages(c.Request.Context(), principal, id, page, pageSize)
	if err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, result)
}

func (h *Handler) send(c *gin.Context, principal Principal) {
	id, ok := parseID(c, "id")
	if !ok {
		return
	}
	var req SendMessageRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "消息格式不正确")
		return
	}
	message, err := h.service.SendMessage(c.Request.Context(), principal, id, req)
	if err != nil {
		writeChatError(c, err)
		return
	}
	response.Created(c, message)
}

func (h *Handler) markRead(c *gin.Context, principal Principal) {
	id, ok := parseID(c, "id")
	if !ok {
		return
	}
	if err := h.service.MarkRead(c.Request.Context(), principal, id); err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, gin.H{"read": true})
}
