package tenants

import (
	"context"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/assert"
)

type fakeS3Fetcher struct {
	bodies map[string]string
	errs   map[string]error
	calls  []struct{ bucket, key string }
}

func (f *fakeS3Fetcher) Fetch(ctx context.Context, bucket, key string) (string, error) {
	f.calls = append(f.calls, struct{ bucket, key string }{bucket, key})
	if err, ok := f.errs[key]; ok {
		return "", err
	}
	return f.bodies[key], nil
}

func TestClusterS3Key(t *testing.T) {
	c := DeletedCluster{ClusterID: "c1", ProjectID: "p1", OrganizationID: "o1"}
	got := clusterS3Key("tidbcloud", c)
	want := "archived/tidbcloud/o1/p1/c1/cluster.yaml"
	assert.Equal(t, want, got)
}

func TestAWSCLIFetcherFetch(t *testing.T) {
	t.Run("ReturnsStdout", func(t *testing.T) {
		dir := t.TempDir()
		argsFile := filepath.Join(dir, "args")
		putOnPATH(t, "aws", recordArgs(argsFile)+`cat <<'EOF'
bizType: tidbcloud
vmAccountId: 1001
vmProjectId: 0
EOF`)

		text, err := NewAWSCLIFetcher().Fetch(context.Background(), "bkt", "archived/tidbcloud/o1/p1/c1/cluster.yaml")
		assert.NoError(t, err)
		assert.Equal(t, "bizType: tidbcloud\nvmAccountId: 1001\nvmProjectId: 0\n", text)
		assert.Equal(t, []string{
			"s3", "cp", "s3://bkt/archived/tidbcloud/o1/p1/c1/cluster.yaml", "-",
		}, readArgs(t, argsFile))
	})

	t.Run("Failure", func(t *testing.T) {
		putOnPATH(t, "aws", `echo "no such key" 1>&2; exit 1`)
		_, err := NewAWSCLIFetcher().Fetch(context.Background(), "bkt", "k")
		assert.ErrorContains(t, err, "s3://bkt/k")
		assert.ErrorContains(t, err, "no such key")
	})
}
