package s2s2

import (
	"net/http"

	logging "code.justin.tv/amzn/TwitchLogging"
	"code.justin.tv/amzn/TwitchS2S2/c7s"
	"code.justin.tv/video/metrics-middleware/v2/operation"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
)

var defaultProductionConfig = c7s.Config{
	AWSRegion:            "us-west-2",
	AccessTokenCacheSize: 1000,
	CalleeRealm:          "TwitchS2S",
	DiscoveryEndpoint:    "https://gateway.us-west-2.prod.s2s.s.twitch.a2z.com/.well-known/openid-configuration",
	Issuer:               "https://gateway.us-west-2.prod.s2s.s.twitch.a2z.com",
	ServiceURIByNameBase: "https://names.prod.services.s2s.twitch.a2z.com",
	TokenScope:           "https://auth.prod.services.s2s.twitch.a2z.com#GetToken",
	EnableAccessLogging:  false,
}

// Options are the optional defaultable clients that s2s requires.
//
// The functions below decide which defaults are loaded if not provided.
type Options struct {
	Config           *c7s.Config
	Credentials      *credentials.Credentials
	Logger           logging.Logger
	OperationStarter *operation.Starter
	RoundTripper     http.RoundTripper
}

func newConfigFromOptions(
	options *Options,
) (*c7s.Config, error) {
	defaultConfig := new(c7s.Config)
	*defaultConfig = defaultProductionConfig
	cfg := defaultConfig.Merge(options.Config)
	if err := cfg.Validate(); err != nil {
		return nil, err
	}
	return cfg, nil
}

func newCredentialsFromOptions(options *Options) *credentials.Credentials {
	if options.Credentials == nil {
		return session.Must(session.NewSession(&aws.Config{})).Config.Credentials
	}
	return options.Credentials
}

func newOperationStarterFromOptions(options *Options) *operation.Starter {
	if options.OperationStarter == nil {
		return &operation.Starter{}
	}
	return options.OperationStarter
}

type noopLogger struct{}

func (noopLogger) Log(string, ...interface{}) {}

func newLoggerFromOptions(
	options *Options,
) logging.Logger {
	if options.Logger == nil {
		return noopLogger{}
	}
	return options.Logger
}

func newRoundTripperFromOptions(
	options *Options,
) http.RoundTripper {
	if options.RoundTripper == nil {
		return http.DefaultTransport
	}
	return options.RoundTripper
}
