package whatsapp

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"strings"
	"wechat-api/ent/predicate"
	"wechat-api/ent/whatsapp"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

func (l *UpdateAllowAndBlockListLogic) UpdateAllowAndBlockList(req *types.UpdateAllowAndBlockListReq) (resp *types.BaseMsgResp, err error) {
	isAdmin := l.ctx.Value("isAdmin").(bool)
	var predicates []predicate.Whatsapp
	if !isAdmin {
		organizationId := l.ctx.Value("organizationId").(uint64)
		predicates = append(predicates, whatsapp.OrganizationID(organizationId))
	}

	var allowListArray []string
	var groupAllowListArray []string
	var blockListArray []string
	var groupBlockListArray []string
	if req.AllowList != nil && *req.AllowList != "" {
		allowListArray = strings.Split(*req.AllowList, "\n")
	} else {
		allowListArray = []string{"ALL"}
	}
	if req.GroupAllowList != nil && *req.GroupAllowList != "" {
		groupAllowListArray = strings.Split(*req.GroupAllowList, "\n")
	} else {
		groupAllowListArray = []string{"ALL"}
	}
	if req.BlockList != nil && *req.GroupAllowList != "" {
		blockListArray = strings.Split(*req.BlockList, "\n")
	} else {
		blockListArray = []string{""}
	}
	if req.GroupBlockList != nil && *req.GroupAllowList != "" {
		groupBlockListArray = strings.Split(*req.GroupBlockList, "\n")
	} else {
		groupBlockListArray = []string{""}
	}
	err = l.svcCtx.DB.Whatsapp.UpdateOneID(req.Id).
		Where(predicates...).
		SetNotNilAllowList(allowListArray).
		SetNotNilGroupAllowList(groupAllowListArray).
		SetNotNilBlockList(blockListArray).
		SetNotNilGroupBlockList(groupBlockListArray).
		Exec(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	_ = l.svcCtx.Rds.Del(l.ctx, "wa_info")

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