// Wrapper package for DynamoDB

package db

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

	"code.justin.tv/foundation/history-worker/configuration"
	"code.justin.tv/foundation/history-worker/custom_aws"
	"code.justin.tv/foundation/history-worker/models"
)

var cachedClient *dynamodb.DynamoDB

const (
	PRIMARY_KEY = "uuid"
)

// Returns the AWS DynamoDB client
func Client() *dynamodb.DynamoDB {
	if cachedClient == nil {
		cachedClient = dynamodb.New(custom_aws.Session())
	}

	return cachedClient
}

// Saves the audit record to DynamoDB
func Add(audit *models.Audit) error {
	params := &dynamodb.PutItemInput{
		TableName: aws.String(configuration.Resolve("dynamodbTableName")),
		Item: map[string]*dynamodb.AttributeValue{
			"uuid":       {S: aws.String(audit.Uuid)},
			"body":       {S: aws.String(audit.Body())},
			"expired_at": {N: aws.String(audit.DynamoExpiredAt())},
		},
		ExpressionAttributeNames: map[string]*string{
			"#uuid": aws.String("uuid"),
		},
		ConditionExpression: aws.String("attribute_not_exists(#uuid)"),
	}

	_, err := Client().PutItem(params)

	return err
}
