package caller

import (
	"errors"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/cactus/go-statsd-client/statsd"

	"code.justin.tv/sse/malachai/pkg/config"
	"code.justin.tv/sse/malachai/pkg/internal/statsdclient"
)

// Config holds config options
type Config struct {
	// optional config to disable secret rotations. if this is set to true,
	// sqs queues will not be created on startup. only disable for short usecases
	// such as lambda, ecs tasks, etc.
	DisableSecretRotationListener bool

	// optional boolean to disable statsd client in dev environments without
	// connectivity to statsd.internal.justin.tv. Production clients should
	// have this set to false and configure proper access to the statsd
	// endpoint
	DisableStatsClient bool

	// optional aws config override
	AWSConfigBase *aws.Config

	// for internal use only
	//
	// Environment should always be set to production or left empty
	Region                    string
	Environment               string
	SandstormKMSKeyID         string
	SandstormSecretsTableName string
	SandstormTopicArn         string
	roleArn                   string

	// To be set by NewRoundTripper / NewWithCustomRoundTripper
	// CallerName is the human-readable name of the service. This is used to
	// discover internal configuration options.
	callerName string
}

// FillDefaults fills in default configuration options. This is called in
// the roundtripper constructor, so the client does not need to call this
// manually.
func (cfg *Config) FillDefaults() (err error) {
	if cfg.AWSConfigBase == nil {
		cfg.AWSConfigBase = aws.NewConfig()
	}

	if cfg.callerName == "" {
		err = errors.New("callerName is required")
		return
	}

	if cfg.Environment == "" {
		cfg.Environment = "production"
	}

	resources, err := config.GetResources(cfg.Environment)
	if err != nil {
		return
	}

	if cfg.Region == "" {
		cfg.Region = resources.Region
	}

	if cfg.SandstormKMSKeyID == "" {
		cfg.SandstormKMSKeyID = resources.SandstormKMSKeyID
	}

	if cfg.SandstormSecretsTableName == "" {
		cfg.SandstormSecretsTableName = resources.SandstormSecretsTableName
	}

	if cfg.SandstormTopicArn == "" {
		cfg.SandstormTopicArn = resources.SandstormTopicArn
	}
	return
}

func (cfg *Config) statsd(serviceName string) (statter statsd.Statter, err error) {
	return statsdclient.NewStatter(cfg.Environment, serviceName, cfg.DisableStatsClient)
}
