package stashing

import (
	"testing"

	"github.com/stretchr/testify/require"
	conf "github.com/tidbcloud/serverless-service/internal/config"
	aws2 "github.com/tidbcloud/serverless-service/internal/infra/aws"
)

func TestGetBucketName(t *testing.T) {
	original := conf.Global()
	t.Cleanup(func() { conf.Set(original) })

	for _, tc := range []struct {
		name   string
		prefix string
		want   string
	}{
		{name: "stage fallback", want: "staging-us-west-2-stashing-area"},
		{name: "configured prefix", prefix: "cp9-proof", want: "cp9-proof-us-west-2-stashing-area"},
	} {
		t.Run(tc.name, func(t *testing.T) {
			conf.Set(&conf.CentralConfig{ServerConfig: conf.ServerConfig{
				Stage:                    conf.StageStaging,
				StashingAreaBucketPrefix: tc.prefix,
			}})
			require.Equal(t, tc.want, (&StashingArea{Region: "us-west-2"}).GetBucketName())
		})
	}
}

func TestNewStashingAreaProviderDoesNotPanicWithoutS3Client(t *testing.T) {
	original := conf.Global()
	t.Cleanup(func() { conf.Set(original) })

	conf.Set(&conf.CentralConfig{
		WorkerConfig: conf.WorkerConfig{
			RegionalConfig: []conf.RegionalConfig{
				{Provider: conf.ProviderGCP, Region: "us-east4"},
				{Provider: conf.ProviderAWS, Region: "us-west-2"},
			},
		},
	})

	require.NotPanics(t, func() {
		s3Provider := &aws2.S3ClientProvider{}
		preSigner := aws2.NewPresignerProvider(s3Provider)
		provider := NewStashingAreaProvider(preSigner, s3Provider)
		_, err := provider.GetStashingArea(conf.ProviderGCP, "us-east4")
		require.Error(t, err)
	})
}
