package chat

import (
	"hfb_sys/backend/pkg/response"

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

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(c.Request.Context(), principal, page, pageSize, filter)
	if err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, result)
}

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) 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) 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) 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(c.Request.Context(), 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(c.Request.Context())
	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(c.Request.Context(), principal, id, req); err != nil {
		writeChatError(c, err)
		return
	}
	response.OK(c, gin.H{"updated": true})
}
