package slprober

import (
	"context"
	"time"

	"github.com/pingcap/log"
	"go.uber.org/zap"

	"github.com/tidbcloud/sli-reporter/slprober/handshake"
)

type serviceResult struct {
	success     bool
	addr        string
	serviceName string
}

// probeTiDBService probes a Service (tidb/tiproxy)
func probeTiDBService(ctx context.Context,
	addr string,
	serviceName string,
	resultCh chan<- serviceResult,
	handshakeCli handshake.Interface,
) {
	logger := log.L().With(zap.String("addr", addr), zap.String("serviceName", serviceName))
	logger.Info("begin probe service")
	timeBegin := time.Now()
	_, err := handshakeCli.TryConnect(ctx, addr)
	result := serviceResult{
		success:     true,
		addr:        addr,
		serviceName: serviceName,
	}
	if err != nil {
		logger.Error("probe service failed", zap.Error(err),
			zap.String("elapsed", time.Since(timeBegin).String()),
		)
		result.success = false
	}

	select {
	case <-ctx.Done():
		logger.Info("finish probe service, context done",
			zap.Bool("success", result.success),
			zap.String("elapsed", time.Since(timeBegin).String()),
		)
		return
	case resultCh <- result:
		logger.Info("finish probe service",
			zap.Bool("success", result.success),
			zap.String("elapsed", time.Since(timeBegin).String()),
		)
		return
	}
}
