package registration

import (
	"context"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/dynamodb"
	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)

// ListServiceNamesOutput is returned from ListServiceNames
type ListServiceNamesOutput struct {
	ServiceNames []string
}

// ListServiceNames returns the full list of service names in the registration
// table.
func (reg *registrar) ListServiceNames(ctx context.Context) (output *ListServiceNamesOutput, err error) {
	output = &ListServiceNamesOutput{
		ServiceNames: make([]string, 0, 100),
	}
	err = reg.db.ScanPages(&dynamodb.ScanInput{
		TableName:            aws.String(reg.cfg.TableName),
		ProjectionExpression: aws.String("service_name"),
	}, func(page *dynamodb.ScanOutput, lastPage bool) bool {
		for _, item := range page.Items {
			svc := &Service{}
			err = dynamodbattribute.UnmarshalMap(item, svc)
			if err != nil {
				return false
			}

			output.ServiceNames = append(output.ServiceNames, svc.Name)
		}
		return !lastPage
	})
	return
}
