package handlers

import (
	"net/http"
	"strings"

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

// GetAllConversations 返回所有用户会话列表。
func (h *AdminHandler) GetAllConversations(c *gin.Context) {
	if !h.requireAdmin(c) {
		return
	}
	convs, err := h.chatStore.ListConversations()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": gin.H{"conversations": convs}})
}

// GetConversation 返回指定账号的全部消息记录。
func (h *AdminHandler) GetConversation(c *gin.Context) {
	if !h.requireAdmin(c) {
		return
	}
	accountID := c.Param("account")
	if accountID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
		return
	}
	msgs, err := h.chatStore.GetMessages(accountID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": gin.H{"messages": msgs}})
}

type adminChatPayload struct {
	Content string `json:"content"`
}

// AdminReply 向指定用户发送管理员回复。
func (h *AdminHandler) AdminReply(c *gin.Context) {
	if !h.requireAdmin(c) {
		return
	}
	accountID := c.Param("account")
	if accountID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
		return
	}
	var payload adminChatPayload
	if err := c.ShouldBindJSON(&payload); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
		return
	}
	content := strings.TrimSpace(payload.Content)
	if content == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "消息不能为空"})
		return
	}
	msg, err := h.chatStore.SendAdminMessage(accountID, content)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}})
}

// ClearConversation 清除与指定用户的全部消息记录。
func (h *AdminHandler) ClearConversation(c *gin.Context) {
	if !h.requireAdmin(c) {
		return
	}
	accountID := c.Param("account")
	if accountID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
		return
	}
	if err := h.chatStore.ClearConversation(accountID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
}
