// +build integration

package storage_test

import (
	"context"
	"testing"
	"time"

	"code.justin.tv/creator-collab/log"
	"code.justin.tv/live/autohost/internal/hosting/config"
	"code.justin.tv/live/autohost/internal/hosting/storage"
	"code.justin.tv/live/autohost/internal/localdynamo"
	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
	"github.com/stretchr/testify/require"
)

type testEnv struct {
	localTables    *localdynamo.Tables
	storageClient  storage.Storage
	dynamoDBClient dynamodbiface.DynamoDBAPI
	hostTableName  string
}

func newTestEnv(t *testing.T) *testEnv {
	conf, err := config.GetConfig()
	require.NoError(t, err)
	require.NotNil(t, conf)
	require.NotEmpty(t, conf.DynamoDB.LocalDynamoEndpoint)
	require.NotEmpty(t, conf.DynamoDB.HostTableName)

	logger := log.NewDevelopmentLogger()

	localTables, err := localdynamo.NewLocalDynamoTables(conf.DynamoDB.LocalDynamoEndpoint, logger)
	require.NoError(t, err)

	localDynamoClient, err := localdynamo.NewLocalDynamoDBClient(conf.DynamoDB.LocalDynamoEndpoint)
	require.NoError(t, err)

	storageClient := storage.New(&storage.Params{
		Client:            localDynamoClient,
		Logger:            log.NewDevelopmentLogger(),
		HostTableName:     conf.DynamoDB.HostTableName,
		SettingsTableName: conf.DynamoDB.SettingsTableName,
	})

	return &testEnv{
		localTables:    localTables,
		storageClient:  storageClient,
		dynamoDBClient: localDynamoClient,
		hostTableName:  localdynamo.TableHost,
	}
}

func (e *testEnv) reset(t *testing.T) {
	err := e.localTables.Reset()
	require.NoError(t, err)
}

func getContextWithTimeout() (context.Context, context.CancelFunc) {
	return context.WithTimeout(context.Background(), time.Second)
}
