package policy

import (
	"path"

	"code.justin.tv/systems/sandstorm/resource"
)

// Config holds the configration about IAM generator.
type Config struct {
	Environment string

	// ARN of pre-existing policy allowing sns/sqs/kms actions
	AuxPolicyArn string

	// ARN of policy similar to AuxPolicyArn but also KMS:GenerateDataKey
	RWAuxPolicyArn string

	// ARN of DynamoDB table containing secrets
	DynamoDBSecretsTableArn      string
	DynamoDBSecretsAuditTableArn string
	DynamoDBNamespaceTableArn    string

	// Table name of RoleOwner Table
	RoleOwnerTableName string

	// path prefixes for iam policy/roles
	IAMPathPrefix string

	// Account id which holds all iam resources.
	AccountID string
}

const (
	defaultEnvironment = "production"
)

// DefaultConfig returns configuration that should be used to load
// policyGenerator with default production config.
func DefaultConfig() (cfg *Config, err error) {
	return GetDefaultConfigForEnvironment(defaultEnvironment)
}

// GetDefaultConfigForEnvironment returns configs required to correctly configure Pg for specified env.
func GetDefaultConfigForEnvironment(env string) (cfg *Config, err error) {

	res, err := resource.GetConfigForEnvironment(env)
	if err != nil {
		return
	}

	cfg = &Config{
		Environment:                  env,
		AuxPolicyArn:                 res.AuxPolicyArn,
		RWAuxPolicyArn:               res.RWAuxPolicyArn,
		DynamoDBSecretsTableArn:      res.SandstormTableArn,
		DynamoDBSecretsAuditTableArn: res.SandstormAuditTableArn,
		DynamoDBNamespaceTableArn:    res.NamespaceTableArn,
		RoleOwnerTableName:           res.RoleOwnerTableName,
		AccountID:                    res.AccountID,
		IAMPathPrefix:                "/" + path.Join("sandstorm", env) + "/",
	}
	return
}

func fillDefaultConfig(provided *Config) (err error) {
	def, err := DefaultConfig()
	if err != nil {
		return
	}
	if provided == nil {
		provided = def
	}

	if provided.AuxPolicyArn == "" {
		provided.AuxPolicyArn = def.AuxPolicyArn
	}
	if provided.RWAuxPolicyArn == "" {
		provided.RWAuxPolicyArn = def.RWAuxPolicyArn
	}
	if provided.DynamoDBSecretsTableArn == "" {
		provided.DynamoDBSecretsTableArn = def.DynamoDBSecretsTableArn
	}
	if provided.DynamoDBSecretsAuditTableArn == "" {
		provided.DynamoDBSecretsAuditTableArn = def.DynamoDBSecretsAuditTableArn
	}
	if provided.DynamoDBNamespaceTableArn == "" {
		provided.DynamoDBNamespaceTableArn = def.DynamoDBNamespaceTableArn
	}
	if provided.RoleOwnerTableName == "" {
		provided.RoleOwnerTableName = def.RoleOwnerTableName
	}
	if provided.AccountID == "" {
		provided.AccountID = def.AccountID
	}
	if provided.IAMPathPrefix == "" {
		provided.IAMPathPrefix = def.IAMPathPrefix
	}
	return
}
