package nats

import (
	"fmt"
	"leaf/log"
	"os"
	"os/signal"
	"testing"
	"time"
)

func TestNats(t *testing.T) {
	// 创建配置
	cfg := Config{
		Servers:        []string{"nats://localhost:4222"},
		ClientName:     "my-service",
		ConnectTimeout: 5 * time.Second,
		PingInterval:   30 * time.Second,
		MaxReconnects:  10,
		ReconnectWait:  2 * time.Second,
	}

	// 初始化集群
	cluster, err := NewNATSCluster(cfg)
	if err != nil {
		panic(err)
	}

	// 注册普通处理器
	cluster.RegisterHandler("account", onAccountSystem)

	// 注册负载均衡处理器
	cluster.RegisterQueueHandler("order", "order-processors", func(data []byte) {
		// 处理订单请求
	})

	// 同步调用
	resp, err := cluster.Request("payment", []byte("data"), 3*time.Second)
	if err != nil {
		log.Error(err.Error())
	}
	log.Debug("resp:", string(resp))

	// 异步调用
	err = cluster.Call("notification", []byte("msg"))

	// close
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)
	sig := <-c
	log.Release("redis_test closing down (signal: %v)", sig)
	// 关闭连接
	cluster.Close()
}

func onAccountSystem(data []byte) {
	fmt.Println("recv accountsystem msg:")
	fmt.Println(string(data))
}
