package api_key

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

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

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

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

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

func (l *UpdateApiKeyLogic) UpdateApiKey(req *types.ApiKeyInfo) (resp *types.BaseMsgResp, err error) {
	err = l.svcCtx.DB.ApiKey.UpdateOneID(*req.Id).
		SetNotNilTitle(req.Title).
		SetNotNilAgentID(req.AgentId).
		SetNotNilCustomAgentBase(req.CustomAgentBase).
		SetNotNilCustomAgentKey(req.CustomAgentKey).
		SetNotNilOpenaiBase(req.OpenaiBase).
		SetNotNilOpenaiKey(req.OpenaiKey).
		Exec(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	l.svcCtx.Rds.Del(l.ctx, "api_key")
	return &types.BaseMsgResp{Msg: errormsg.UpdateSuccess}, nil
}
