package tests

import (
	"encoding/json"
	"net/http"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/pingcap/dbaas/billing2/api"
	"github.com/pingcap/dbaas/billing2/config"
	"github.com/pingcap/dbaas/billing2/forms"
	"github.com/pingcap/dbaas/billing2/utils/ginutils"
	"github.com/pingcap/dbaas/billing2/utils/tests"
	"github.com/stretchr/testify/suite"
)

type SwitchTestSuite struct {
	tests.BillingTestSuite
	router *gin.Engine
}

func (suite *SwitchTestSuite) SetupTest() {
	suite.BillingTestSuite.SetupTest()
	suite.router = gin.New()
	suite.router.Use(ginutils.ErrorMiddleWare)
	api.InitializeSwitchRouter(ginutils.MyRoute{Route: suite.router})
}

func TestSwitchSuite(t *testing.T) {
	suite.Run(t, new(SwitchTestSuite))
}

func (suite *SwitchTestSuite) TestIsCreditCardValidateAllowed() {
	assert := suite.Assert()
	switchStruct := &forms.SwitchResponse{}

	// test case 1
	config.Get().SetDefault(config.IsCreditCardValidateAllowed, false)
	w := tests.PerformRequest(suite.router, "GET", "/tenants/1/switch/card/validate/is_allowed", nil)
	assert.Equal(http.StatusOK, w.Code)
	err := json.NewDecoder(w.Body).Decode(switchStruct)
	assert.NoError(err)
	assert.Equal(switchStruct.IsAllowed, false)
	assert.Equal(switchStruct.TenantID, uint(1))

	// test case 2
	config.Get().SetDefault(config.IsCreditCardValidateAllowed, true)
	config.Get().SetDefault(config.CreditCardValidateAllowedTenants, "1#2")
	w = tests.PerformRequest(suite.router, "GET", "/tenants/1/switch/card/validate/is_allowed", nil)
	assert.Equal(http.StatusOK, w.Code)
	err = json.NewDecoder(w.Body).Decode(switchStruct)
	assert.NoError(err)
	assert.Equal(switchStruct.IsAllowed, true)

	// test case 3
	config.Get().SetDefault(config.IsCreditCardValidateAllowed, true)
	config.Get().SetDefault(config.CreditCardValidateAllowedTenants, "2#3#4")
	w = tests.PerformRequest(suite.router, "GET", "/tenants/1/switch/card/validate/is_allowed", nil)
	assert.Equal(http.StatusOK, w.Code)
	err = json.NewDecoder(w.Body).Decode(switchStruct)
	assert.NoError(err)
	assert.Equal(switchStruct.IsAllowed, false)

	// test case 4
	config.Get().SetDefault(config.IsCreditCardValidateAllowed, true)
	config.Get().SetDefault(config.CreditCardValidateAllowedTenants, "all")
	w = tests.PerformRequest(suite.router, "GET", "/tenants/1/switch/card/validate/is_allowed", nil)
	assert.Equal(http.StatusOK, w.Code)
	err = json.NewDecoder(w.Body).Decode(switchStruct)
	assert.NoError(err)
	assert.Equal(switchStruct.IsAllowed, true)
}
