package inventory

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"
)

// Key is the composite key for an instance in the inventory dynamodb
type Key struct {
	ServiceID  string `dynamodbav:"service_id"`
	InstanceID string `dynamodbav:"instance_id"`
}

// ListServiceInstancesInput is the input for ListServiceInstances
type ListServiceInstancesInput struct {
	ServiceID string
	First     int32
	After     *Key
}

// ListServiceInstancesOutput is the output of ListServiceInstances
type ListServiceInstancesOutput struct {
	Items   []*Instance
	HasNext bool
}

// ListServiceInstances returns a page of service instances
func (client *Client) ListServiceInstances(ctx context.Context, input *ListServiceInstancesInput) (output *ListServiceInstancesOutput, err error) {
	var exclusiveStartKey map[string]*dynamodb.AttributeValue
	if input.After != nil {
		exclusiveStartKey, err = dynamodbattribute.MarshalMap(input.After)
		if err != nil {
			return
		}
	}

	queryInput := &dynamodb.QueryInput{
		ExclusiveStartKey: exclusiveStartKey,
		ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
			":service_id": {S: aws.String(input.ServiceID)},
		},
		Limit:                  aws.Int64(int64(input.First)),
		KeyConditionExpression: aws.String("service_id = :service_id"),
		TableName:              aws.String(client.config.TableName),
	}

	queryOutput, err := client.db.QueryWithContext(ctx, queryInput)
	if err != nil {
		return
	}

	output = &ListServiceInstancesOutput{
		Items:   make([]*Instance, len(queryOutput.Items)),
		HasNext: queryOutput.LastEvaluatedKey != nil,
	}

	for nItem, item := range queryOutput.Items {
		i := &Instance{}
		err = i.UnmarshalDynamoDBMap(item)
		if err != nil {
			return
		}
		output.Items[nItem] = i
	}

	return
}
