package manager

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

// List lists secrets by calling a dynamodb.Scan over active secrets
func (m *Manager) List() ([]*Secret, error) {
	var secrets []*Secret
	err := m.statter.WithMeasuredResult("secret.list", nil, func() (err error) {
		scanInput := m.inputForListScan()
		for {
			var scanOutput *dynamodb.ScanOutput
			scanOutput, err = m.dynamoDB().Scan(scanInput)
			if err != nil {
				return
			}
			var secret *Secret
			for _, item := range scanOutput.Items {
				secret, err = unmarshalSecret(item)
				if err != nil {
					return
				}
				secrets = append(secrets, secret)
			}

			if scanOutput.LastEvaluatedKey == nil {
				break
			} else {
				scanInput.ExclusiveStartKey = scanOutput.LastEvaluatedKey
			}
		}
		return
	})
	if err != nil {
		return nil, err
	}
	return secrets, nil
}

func (m *Manager) inputForListScan() *dynamodb.ScanInput {
	return &dynamodb.ScanInput{
		ReturnConsumedCapacity: aws.String("INDEXES"),
		TableName:              aws.String(m.Config.stack().SecretsTableName()),
	}
}
