package receive

import (
	"context"
	"fmt"
	"os"

	"github.com/tidbcloud/account/commons/redis"

	"go.uber.org/zap"

	"github.com/tidbcloud/account/thirdparty/infra"

	"github.com/tidbcloud/tiinf/monitor/tilog"
)

const redisChanel = "DeleteClusterCache"

func RedisSubscribe(ctx context.Context) {
	tilog.Info(ctx, "Redis Subscribe start")
	go infra.DelAllClusterCache(ctx)
	pubsub := redis.GetRedisClient().Subscribe(ctx, redisChanel)
	hostname, _ := os.Hostname()
	tilog.Info(ctx, "Redis Subscribe Channel")
	ch := pubsub.Channel()
	for msg := range ch {
		tilog.Info(ctx, "Redis Subscribe  receive message", zap.Any("msg.Payload", msg.Payload), zap.Any("hostname", hostname))
		clusterId := msg.Payload
		deleteClusterCache(ctx, clusterId)
	}

}
func deleteClusterCache(ctx context.Context, clusterId string) {

	c := infra.GetClusterCache(ctx)
	c.Delete(clusterId)
	tilog.Info(ctx, fmt.Sprintf("delete cluster cache ,cluster_id=%v", clusterId))
}
