package admin

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"

	"mini-chat/internal/code"
	"mini-chat/internal/pkg/core"
	"mini-chat/internal/pkg/validation"

	"gorm.io/gorm"
)

type relAppRequest struct {
	Ids string `json:"ids" binding:"required"` // 小程序编号(多个用,分割)
}

type relAppResponse struct {
	Message string `json:"message"` // 提示信息
}

// RelApp 客服关联小程序
// @Summary 客服关联小程序
// @Description 客服关联小程序
// @Tags 管理端.客服管理
// @Accept json
// @Produce json
// @Param id path string true "客服编号ID"
// @Param RequestBody body relAppRequest true "请求参数"
// @Success 200 {object} relAppResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin/rel_app/{id} [put]
// @Security LoginVerifyToken
func (h *handler) RelApp() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(relAppRequest)
		res := new(relAppResponse)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				validation.Error(err)),
			)
			return
		}

		if ctx.SessionUserInfo().IsSuper != 1 {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.RelAppError,
				fmt.Sprintf("%s: %s", code.Text(code.RelAppError), "禁止操作")),
			)
			return
		}

		idList := strings.Split(req.Ids, ",")
		if len(idList) == 0 || (len(idList) == 1 && idList[0] == "") {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				"编号不能为空"),
			)
			return
		}

		var ids []int32

		for _, strID := range idList {
			if strID == "" {
				continue
			}

			id, err := strconv.Atoi(strID)
			if err != nil {
				ctx.AbortWithError(core.Error(
					http.StatusBadRequest,
					code.ParamBindError,
					fmt.Sprintf("无效的编号: %s", strID)),
				)
				return
			}

			ids = append(ids, int32(id))
		}

		if len(ids) == 0 {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				"编号不能为空"),
			)
			return
		}

		adminID, err := strconv.Atoi(ctx.Param("id"))
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				"未传递客服编号ID"),
			)
			return
		}

		checkInfo, err := h.readDB.Admin.WithContext(ctx.RequestContext()).
			Where(h.readDB.Admin.ID.Eq(int32(adminID))).
			First()
		if err != nil && err != gorm.ErrRecordNotFound {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.RelAppError,
				fmt.Sprintf("%s: %s", code.Text(code.RelAppError), err.Error())),
			)
			return
		}

		if checkInfo == nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.RelAppError,
				fmt.Sprintf("%s: %s", code.Text(code.RelAppError), "该客服不存在")),
			)
			return
		}

		if checkInfo.IsSuper == 1 {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.RelAppError,
				fmt.Sprintf("%s", "作为超级管理员，您拥有无需关联即可查看的权限。")),
			)
			return
		}

		if _, err := h.writeDB.MiniProgram.WithContext(ctx.RequestContext()).
			Where(h.writeDB.MiniProgram.ID.In(ids...)).
			Updates(map[string]interface{}{
				"admin_id":     adminID,
				"updated_user": ctx.SessionUserInfo().UserName,
				"updated_at":   time.Now(),
			}); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.RelAppError,
				fmt.Sprintf("%s: %s", code.Text(code.RelAppError), err.Error())),
			)
			return
		}

		res.Message = "操作成功"
		ctx.Payload(res)
	}
}
