package ddb

import (
	"context"
	"time"

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

func CreateTableForGlobal(ctx context.Context, cli *dynamodb.Client, createTableInput *dynamodb.CreateTableInput) (*types.TableDescription, error) {
	createTableInput.StreamSpecification = &types.StreamSpecification{
		StreamEnabled:  aws.Bool(true),
		StreamViewType: types.StreamViewTypeNewAndOldImages,
	}
	return CreateTable(ctx, cli, createTableInput)
}

// CreateTableReplica create replica table for global table of Version 2019.11.21
func CreateTableReplica(ctx context.Context, cli *dynamodb.Client, tableName, region string) error {
	_, err := cli.UpdateTable(ctx, &dynamodb.UpdateTableInput{
		TableName: &tableName,
		ReplicaUpdates: []types.ReplicationGroupUpdate{
			{
				Create: &types.CreateReplicationGroupMemberAction{
					RegionName: &region,
				},
			},
		},
	})
	return err
}

// DeleteTableReplica delete replica table for global table of Version 2019.11.21
func DeleteTableReplica(ctx context.Context, cli *dynamodb.Client, tableName, region string) error {
	_, err := cli.UpdateTable(ctx, &dynamodb.UpdateTableInput{
		TableName: &tableName,
		ReplicaUpdates: []types.ReplicationGroupUpdate{
			{
				Delete: &types.DeleteReplicationGroupMemberAction{
					RegionName: &region,
				},
			},
		},
	})
	return err
}

// CreateGlobalTable create global table in specified regions.
// You should use CreateTableForGlobal to create a table in another region before call this API.
func CreateGlobalTable(ctx context.Context, cli *dynamodb.Client, tableName string, regions []string) error {

	// replicas := make([]types.Replica, len(regions))
	// for i, r := range regions {
	// 	replicas[i] = types.Replica{RegionName: aws.String(r)}
	// }
	// _, err := cli.CreateGlobalTable(ctx, &dynamodb.CreateGlobalTableInput{
	// 	GlobalTableName:  aws.String(tableName),
	// 	ReplicationGroup: replicas,
	// })
	// return err
	for _, region := range regions {
		if err := CreateTableReplica(ctx, cli, tableName, region); err != nil {
			return err
		}
		time.Sleep(time.Second * 10)
	}
	return nil
}

// DeleteGlobalTable delete all replica tables of global table
func DeleteGlobalTable(ctx context.Context, cli *dynamodb.Client, tableName string, regions []string) error {

	for _, region := range regions {
		if err := DeleteTableReplica(ctx, cli, tableName, region); err != nil {
			return err
		}
	}
	return nil
}
