package whatsapp

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

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

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

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

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

func (l *UpdateAgentLogic) UpdateAgent(req *types.UpdateAgentReq) (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))
	}

	err = l.svcCtx.DB.Whatsapp.UpdateOneID(req.Id).
		Where(predicates...).
		SetNotNilAgentID(&req.AgentId).
		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
}
