package handlers

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"

	"mengyastore-backend/internal/auth"
	"mengyastore-backend/internal/storage"
)

type ChatHandler struct {
	chatStore  *storage.ChatStore
	authClient *auth.SproutGateClient
}

func NewChatHandler(chatStore *storage.ChatStore, authClient *auth.SproutGateClient) *ChatHandler {
	return &ChatHandler{chatStore: chatStore, authClient: authClient}
}

func (h *ChatHandler) requireChatUser(c *gin.Context) (account, name string, ok bool) {
	authHeader := c.GetHeader("Authorization")
	if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
		return "", "", false
	}
	token := strings.TrimPrefix(authHeader, "Bearer ")
	result, err := h.authClient.VerifyToken(token)
	if err != nil || !result.Valid || result.User == nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期，请重新登录"})
		return "", "", false
	}
	return result.User.Account, result.User.Username, true
}

// GetMyMessages 返回当前登录用户的全部聊天消息。
// @Summary 我的聊天消息
// @Tags 聊天（用户）
// @Produce json
// @Security BearerAuth
// @Success 200 {object} SwaggerMessagesWrap
// @Failure 401 {object} SwaggerErrorBody
// @Failure 500 {object} SwaggerErrorBody
// @Router /api/chat/messages [get]
func (h *ChatHandler) GetMyMessages(c *gin.Context) {
	account, _, ok := h.requireChatUser(c)
	if !ok {
		return
	}
	msgs, err := h.chatStore.GetMessages(account)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": gin.H{"messages": msgs}})
}

// ChatMessagePayload 用户发送消息请求体。
type ChatMessagePayload struct {
	Content string `json:"content"`
}

// SendMyMessage 向管理员发送一条用户消息。
// @Summary 发送用户消息
// @Tags 聊天（用户）
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body ChatMessagePayload true "消息正文"
// @Success 200 {object} SwaggerOneChatMsgWrap
// @Failure 400 {object} SwaggerErrorBody
// @Failure 401 {object} SwaggerErrorBody
// @Failure 429 {object} SwaggerErrorBody
// @Failure 500 {object} SwaggerErrorBody
// @Router /api/chat/messages [post]
func (h *ChatHandler) SendMyMessage(c *gin.Context) {
	account, name, ok := h.requireChatUser(c)
	if !ok {
		return
	}
	var payload ChatMessagePayload
	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, rateLimited, err := h.chatStore.SendUserMessage(account, name, content)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	if rateLimited {
		c.JSON(http.StatusTooManyRequests, gin.H{"error": "发送太频繁，请稍候"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}})
}
