package caller

import (
	"errors"

	"github.com/aws/aws-sdk-go/aws"

	"code.justin.tv/sse/malachai/pkg/config"
	"code.justin.tv/sse/malachai/pkg/internal/stats/statsiface"
	"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

	// StatsReporter telemetry stats reporter
	StatsReporter statsiface.ReporterAPI
}

// 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"
	}

	if cfg.StatsReporter == nil {
		cfg.StatsReporter, err = statsdclient.NewReporter(cfg.Environment, cfg.callerName, cfg.DisableStatsClient)
		if err != nil {
			return
		}
	}
	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
}
