package contact

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent/wx"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/zeromicro/go-zero/core/logx"
)

type ChangeBlockListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewChangeBlockListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangeBlockListLogic {
	return &ChangeBlockListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *ChangeBlockListLogic) ChangeBlockList(req *types.ChangeBlockListReq) (resp *types.BaseMsgResp, err error) {
	wxInfo, err := l.svcCtx.DB.Wx.Query().Where(wx.Wxid(req.OwnerWxid)).Only(l.ctx)
	if wxInfo == nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	// 根据请求类型选择对应的黑名单列表
	blockList := wxInfo.BlockList
	if *req.Type != 1 {
		blockList = wxInfo.GroupBlockList
	}

	if contains(blockList, "ALL") {
		return nil, errorx.NewDefaultError("请先在账号管理中，取消所属账号的全部黑名单设置")
	}

	isInBlockList := contains(blockList, req.Wxid)
	shouldUpdateBlockList := (*req.Ai && isInBlockList) || (!*req.Ai && !isInBlockList)

	if shouldUpdateBlockList {
		// 更新黑名单: 如果是Ai，移除；如果不是Ai，添加
		if *req.Ai {
			blockList = removeElement(blockList, req.Wxid)
		} else {
			blockList = append(blockList, req.Wxid)
		}

		updateQuery := l.svcCtx.DB.Wx.Update().Where(wx.Wxid(req.OwnerWxid))
		if *req.Type == 1 {
			updateQuery.SetBlockList(blockList)
		} else {
			updateQuery.SetNotNilGroupBlockList(blockList)
		}

		err = updateQuery.Exec(l.ctx)
		if err != nil {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
		l.svcCtx.Rds.HDel(l.ctx, "wx_info", req.OwnerWxid)
	}

	return &types.BaseMsgResp{Msg: errormsg.UpdateSuccess}, nil
}

func contains(slice []string, element string) bool {
	for _, elem := range slice {
		if elem == element {
			return true
		}
	}
	return false
}

func removeElement(slice []string, element string) []string {
	for i, elem := range slice {
		if elem == element {
			return append(slice[:i], slice[i+1:]...)
		}
	}
	return slice
}
