package client

import (
	"net/http"

	infrarpc "code.justin.tv/eventbus/controlplane/infrastructure/rpc"
	"code.justin.tv/eventbus/controlplane/rpc"
	"github.com/pkg/errors"

	"code.justin.tv/eventbus/admin-cli/internal/environment"
)

func NewServices(config *environment.Environment) (rpc.Services, error) {
	var httpClient *http.Client
	var err error
	if httpClient, err = initHTTPClient(config); err != nil {
		return nil, errors.Wrap(err, "could not initialize http client")
	}
	c := rpc.NewServicesProtobufClient(config.BaseURL, httpClient)
	return c, nil
}

func NewInfrastructure(config *environment.Environment) (infrarpc.Infrastructure, error) {
	var httpClient *http.Client
	var err error
	if httpClient, err = initHTTPClient(config); err != nil {
		return nil, errors.Wrap(err, "could not initialize http client")
	}
	c := infrarpc.NewInfrastructureProtobufClient(config.BaseURL, httpClient)
	return c, nil
}

func NewEventStreams(config *environment.Environment) (rpc.EventStreams, error) {
	var httpClient *http.Client
	var err error
	if httpClient, err = initHTTPClient(config); err != nil {
		return nil, errors.Wrap(err, "could not initialize http client")
	}
	c := rpc.NewEventStreamsProtobufClient(config.BaseURL, httpClient)
	return c, nil
}

func NewFeatureFlags(config *environment.Environment) (rpc.FeatureFlags, error) {
	var httpClient *http.Client
	var err error
	if httpClient, err = initHTTPClient(config); err != nil {
		return nil, errors.Wrap(err, "could not initialize http client")
	}
	c := rpc.NewFeatureFlagsProtobufClient(config.BaseURL, httpClient)
	return c, nil
}

func initHTTPClient(config *environment.Environment) (*http.Client, error) {
	httpClient := &http.Client{}
	httpClient.Transport = http.DefaultTransport
	if config.S2SEnabled {
		err := injectS2SRoundTripper(httpClient, config.S2SName)
		if err != nil {
			return nil, errors.Wrap(err, "could not initialize S2S")
		}
	}
	httpClient.Transport = ldapRoundTripper(httpClient.Transport)
	return httpClient, nil
}
