package chat

import (
	"errors"
	"net/http"
	"strconv"

	"hfb_sys/backend/internal/middleware"
	"hfb_sys/backend/pkg/response"

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

type Handler struct {
	service *Service
}

func NewHandler(service *Service) *Handler {
	return &Handler{service: service}
}

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) AdminList(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	filter := c.DefaultQuery("filter", "all")
	page, pageSize := parsePagination(c)
	principal := Principal{Type: "admin", ID: adminID}
	result, err := h.service.ListConversationsWithFilter(principal, page, pageSize, filter)
	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) AdminDetail(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	h.detail(c, Principal{Type: "admin", ID: adminID})
}

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(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(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) AdminMessages(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	h.messages(c, Principal{Type: "admin", ID: adminID})
}

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) AdminSend(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	h.send(c, Principal{Type: "admin", ID: adminID})
}

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})
}

func (h *Handler) AdminMarkRead(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	h.markRead(c, Principal{Type: "admin", ID: adminID})
}

func (h *Handler) AdminTransfer(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	id, ok := parseID(c, "id")
	if !ok {
		return
	}
	var req TransferRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "目标客服 ID 不能为空")
		return
	}
	principal := Principal{Type: "admin", ID: adminID}
	if err := h.service.TransferConversation(principal, id, req); err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, gin.H{"transferred": true})
}

func (h *Handler) AdminSupportAdmins(c *gin.Context) {
	admins, err := h.service.GetAvailableSupportAdmins()
	if err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, admins)
}

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

func (h *Handler) AdminListQuickReplies(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	replies, err := h.service.ListQuickReplies(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(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(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(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()
	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(req.Message); err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, gin.H{"updated": true})
}

func (h *Handler) list(c *gin.Context, principal Principal) {
	page, pageSize := parsePagination(c)
	result, err := h.service.ListConversations(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(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(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(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(principal, id); err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, gin.H{"read": true})
}

func parsePagination(c *gin.Context) (int, int) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
	return normalizePagination(page, pageSize)
}

func parseID(c *gin.Context, key string) (uint64, bool) {
	id, err := strconv.ParseUint(c.Param(key), 10, 64)
	if err != nil || id == 0 {
		response.BadRequest(c, "ID 不正确")
		return 0, false
	}
	return id, true
}

func currentUserID(c *gin.Context) (uint64, bool) {
	value, ok := c.Get(middleware.ContextUserID)
	if !ok {
		return 0, false
	}
	userID, ok := value.(uint64)
	return userID, ok
}

func currentAdminID(c *gin.Context) (uint64, bool) {
	value, ok := c.Get(middleware.ContextAdminID)
	if !ok {
		return 0, false
	}
	adminID, ok := value.(uint64)
	return adminID, ok
}

func writeChatError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, ErrDependencyUnavailable):
		response.ServiceUnavailable(c, "聊天服务暂时不可用")
	case errors.Is(err, ErrConversationNotFound):
		response.Error(c, http.StatusNotFound, "chat_not_found", "会话不存在")
	case errors.Is(err, ErrPermissionDenied):
		response.Error(c, http.StatusForbidden, "permission_denied", "无权访问该会话")
	case errors.Is(err, ErrInvalidMessage):
		response.BadRequest(c, "消息内容不符合规则")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "聊天服务暂时不可用")
	}
}
