package internal

import (
	"code.justin.tv/sse/malachai/pkg/config"
	"code.justin.tv/sse/malachai/pkg/log"
	"code.justin.tv/sse/malachai/pkg/registration"
	"code.justin.tv/sse/malachai/pkg/rorolepicker"
	"github.com/aws/aws-sdk-go/aws"
)

// GetServiceRegistration retrieves a service's registration
func GetServiceRegistration(serviceName, environment string, awsConfigOverride *aws.Config) (*registration.Service, error) {
	res, err := config.GetResources(environment)
	if err != nil {
		return nil, err
	}

	roRoleArn, err := rorolepicker.PickAuxRole(res.ServicesReadOnlyRoleNamePrefix, serviceName, res.ServicesReadOnlyRoleCount)
	if err != nil {
		return nil, err
	}

	regConfig := &registration.Config{
		Environment:   environment,
		RoleArn:       rorolepicker.FormatAuxRoleArn(res.MalachaiAccountID, roRoleArn),
		AWSConfigBase: awsConfigOverride,
	}
	err = regConfig.FillDefaults()
	if err != nil {
		return nil, err
	}

	reg, err := registration.New(regConfig, &log.NoOpLogger{})
	if err != nil {
		return nil, err
	}

	return reg.Get(serviceName)
}
