package manager

import (
	"code.justin.tv/common/ddbmetrics"
	"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
	scanInput := m.inputForListScan()
	for {
		scanOutput, err := m.DynamoDB.Scan(scanInput)
		if err != nil {
			return nil, err
		}
		m.metrics.Report(ddbmetrics.Read, scanOutput.ConsumedCapacity)
		for _, item := range scanOutput.Items {
			secret, err := unmarshalSecret(item)
			if err != nil {
				return nil, err
			}
			secrets = append(secrets, secret)
		}

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

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