package clients

import (
	"context"
	"time"

	commonDomain "github.com/AlchemyTelcoSolutions/utils/service/domain"
	"github.com/pkg/errors"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/keepalive"
)

// initGRPCDial initializes a grpc connection
func initGRPCDial(ctx context.Context, host string) (*grpc.ClientConn, error) {
	if host == "" {
		return nil, errors.New("need to set the grpc hostname")
	}

	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	// by default we create insecure credentials as connection will  be in the same cluster
	conn, err := grpc.DialContext(ctx, host,
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithKeepaliveParams(keepalive.ClientParameters{
			Time:                10 * time.Second, // send pings every 10 seconds if there is no activity
			Timeout:             time.Second,      // wait 1 second for ping back
			PermitWithoutStream: true,
		}),
		grpc.WithBlock(),
	)
	if err != nil {
		return &grpc.ClientConn{}, commonDomain.Wrap(err, "grpc dial failed")
	}

	return conn, nil
}
