package chat

import (
	"hfb_sys/backend/pkg/response"

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

func (h *Handler) AdminListQuickReplies(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	replies, err := h.service.ListQuickReplies(c.Request.Context(), adminID)
	if err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, replies)
}

func (h *Handler) AdminCreateQuickReply(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	var req CreateQuickReplyRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "标题和内容不能为空")
		return
	}
	reply, err := h.service.CreateQuickReply(c.Request.Context(), adminID, req)
	if err != nil {
		writeChatError(c, err)
		return
	}
	response.Created(c, reply)
}

func (h *Handler) AdminUpdateQuickReply(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	id, ok := parseID(c, "id")
	if !ok {
		return
	}
	var req UpdateQuickReplyRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误")
		return
	}
	if err := h.service.UpdateQuickReply(c.Request.Context(), adminID, id, req); err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, gin.H{"updated": true})
}

func (h *Handler) AdminDeleteQuickReply(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	id, ok := parseID(c, "id")
	if !ok {
		return
	}
	if err := h.service.DeleteQuickReply(c.Request.Context(), adminID, id); err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, gin.H{"deleted": true})
}

func (h *Handler) AdminGetAutoWelcome(c *gin.Context) {
	message := h.service.GetAutoWelcomeMessage(c.Request.Context())
	response.OK(c, gin.H{"message": message})
}

func (h *Handler) AdminUpdateAutoWelcome(c *gin.Context) {
	var req struct {
		Message string `json:"message" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "话术内容不能为空")
		return
	}
	if err := h.service.UpdateAutoWelcomeMessage(c.Request.Context(), req.Message); err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, gin.H{"updated": true})
}

func (h *Handler) AdminGetListingGroupWelcome(c *gin.Context) {
	message := h.service.GetListingGroupWelcomeMessage(c.Request.Context())
	response.OK(c, gin.H{"message": message})
}

func (h *Handler) AdminUpdateListingGroupWelcome(c *gin.Context) {
	var req struct {
		Message string `json:"message" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "欢迎语内容不能为空")
		return
	}
	if err := h.service.UpdateListingGroupWelcomeMessage(c.Request.Context(), req.Message); err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, gin.H{"updated": true})
}
