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 UpdateAgentApiLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *UpdateAgentApiLogic) UpdateAgentApi(req *types.UpdateAgentApiReq) (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...).
		SetNotNilAPIBase(req.ApiBase).
		SetNotNilAPIKey(req.ApiKey).
		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
}
