package WechatServer

import (
	"context"

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

	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *UpdateServerLogic) UpdateServer(req *types.ServerInfo) (*types.BaseMsgResp, error) {
	err := l.svcCtx.DB.Server.UpdateOneID(*req.Id).
		SetNotNilStatus(req.Status).
		SetNotNilName(req.Name).
		SetNotNilPublicIP(req.PublicIp).
		SetNotNilPrivateIP(req.PrivateIp).
		SetNotNilAdminPort(req.AdminPort).
		Exec(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	data := map[string]interface{}{
		"private_ip": req.PrivateIp,
		"admin_port": req.AdminPort,
	}
	l.svcCtx.Rds.HSet(l.ctx, "server_info", req.Id, data)
	l.svcCtx.Rds.Del(l.ctx, "crontask_wx_server_info")
	return &types.BaseMsgResp{Msg: errormsg.UpdateSuccess}, nil
}
