package facade_imp

import (
	"os"
	"testing"

	. "github.com/onsi/gomega"
	"github.com/tidbcloud/serverless-service/internal/config"
	"github.com/tidbcloud/serverless-service/internal/domain/constant"
)

func Test_FeatureGateImp_NewFeatureGateImp(t *testing.T) {
	g := NewGomegaWithT(t)
	testCases := []struct {
		configStr   string
		shouldPanic bool
	}{
		{
			`
featureGates:
  test:
    enabledTenants: [".*"]
`,
			true,
		}, {
			`
featureGates:
  test:
    enabledTenants: ["","2","3"]
`,
			true,
		}, {
			`
featureGates:
  test:
    enabledTenants: ["1","2O","3"]
`,
			true,
		}, {
			`
featureGates:
  test:
    enabledTenants: ["1","2","3o"]
`,
			true,
		}, {
			`
featureGates:
  test:
    enabledTenants: []
`,
			false,
		}, {
			`
featureGates:
  test:
`,
			false,
		},
	}

	for _, tc := range testCases {
		f, err := os.CreateTemp(t.TempDir(), "config-test*.yaml")
		g.Expect(err).To(BeNil())
		_, err = f.WriteString(tc.configStr)
		g.Expect(err).To(BeNil())
		err = config.InitConfig(f.Name(), false)
		g.Expect(err).To(BeNil())

		if tc.shouldPanic {
			g.Expect(func() { NewFeatureGateImp() }).To(Panic())
		} else {
			g.Expect(NewFeatureGateImp()).NotTo(BeNil())
		}
	}
}

func Test_FeatureGateImp_FeatureEnabled(t *testing.T) {
	g := NewGomegaWithT(t)
	testCases := []struct {
		configStr   string
		featureName constant.FeatureGateName
		tenantID    []uint64
		region      []string
		expected    []bool
	}{
		{
			``,
			constant.FeatureGateName("test"),
			[]uint64{1, 2, 3},
			[]string{"region1", "region2", "region3"},
			[]bool{false, false, false},
		},
		{
			`
featureGates:
  test:
    enabledTenants: ["*"]
`,
			constant.FeatureGateName("test"),
			[]uint64{1, 2, 3},
			[]string{"region1", "region2", "region3"},
			[]bool{true, true, true},
		},
		{
			`
featureGates:
  test:
    enabledTenants: ["1","3"]
`,
			constant.FeatureGateName("test"),
			[]uint64{1, 2, 3},
			[]string{"region1", "region2", "region3"},
			[]bool{true, false, true},
		},
		{
			`
featureGates:
  test:
    enabledTenants: ["1","3","*"]
`,
			constant.FeatureGateName("test"),
			[]uint64{1, 2, 3},
			[]string{"region1", "region2", "region3"},
			[]bool{true, true, true},
		},
	}

	for _, tc := range testCases {
		f, err := os.CreateTemp(t.TempDir(), "config-test*.yaml")
		g.Expect(err).To(BeNil())
		_, err = f.WriteString(tc.configStr)
		g.Expect(err).To(BeNil())
		err = config.InitConfig(f.Name(), false)
		g.Expect(err).To(BeNil())

		imp := NewFeatureGateImp()
		for i := range tc.tenantID {
			g.Expect(imp.FeatureEnabled(tc.featureName, tc.tenantID[i], tc.region[i])).To(Equal(tc.expected[i]))
		}
	}
}
