package supportgroup

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

	"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) {
	items, err := h.service.List(c.Request.Context())
	if err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, items)
}

func (h *Handler) FindByID(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	item, err := h.service.FindByID(c.Request.Context(), id)
	if err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) Create(c *gin.Context) {
	var req CreateGroupRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "分组名称不能为空")
		return
	}
	item, err := h.service.Create(c.Request.Context(), req)
	if err != nil {
		writeError(c, err)
		return
	}
	response.Created(c, item)
}

func (h *Handler) Update(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	var req UpdateGroupRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "分组名称不能为空")
		return
	}
	item, err := h.service.Update(c.Request.Context(), id, req)
	if err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) Delete(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	if err := h.service.Delete(c.Request.Context(), id); err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, gin.H{"deleted": true})
}

func (h *Handler) AssignMembers(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	var req AssignMembersRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求格式不正确")
		return
	}
	if err := h.service.AssignMembers(c.Request.Context(), id, req); err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, gin.H{"updated": true})
}

func (h *Handler) ListSupportAdmins(c *gin.Context) {
	items, err := h.service.ListSupportAdmins(c.Request.Context())
	if err != nil {
		writeError(c, err)
		return
	}
	response.OK(c, items)
}

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

func writeError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, ErrInvalidGroup):
		response.BadRequest(c, "客服分组信息不正确")
	case errors.Is(err, ErrProtectedGroup):
		response.Error(c, http.StatusConflict, "protected_group", "默认分组不能删除")
	case IsNotFound(err):
		response.NotFound(c, "客服分组不存在")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "客服分组操作失败")
	}
}
