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

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

func (l *CreateServerLogic) CreateServer(req *types.ServerInfo) (*types.BaseMsgResp, error) {
	serverInfo, err := l.svcCtx.DB.Server.Create().
		SetNotNilStatus(req.Status).
		SetNotNilName(req.Name).
		SetNotNilPublicIP(req.PublicIp).
		SetNotNilPrivateIP(req.PrivateIp).
		SetNotNilAdminPort(req.AdminPort).
		Save(l.ctx)

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