package tests

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

	"github.com/pingcap/dbaas/billing2/db/entity"
	"github.com/pingcap/dbaas/billing2/utils/tests/datainit"

	"github.com/gin-gonic/gin"
	"github.com/pingcap/dbaas/billing2/api"
	"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 ControlTestSuite struct {
	tests.BillingTestSuite
	router *gin.Engine
}

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

func TestControlTestSuite(t *testing.T) {
	suite.Run(t, new(ControlTestSuite))
}

func (suite *ControlTestSuite) TestActionCheck() {
	tests.MockCentralHandler()
	assert := suite.Assert()
	provider := forms.Provider_GCP
	actionInfo := forms.BillingActionInfo{
		Action: forms.BillingAction_Create,
		Resource: forms.BillingResource{
			Type:     forms.BillingResourceType_DedicatedCluster,
			Provider: &provider,
			IsFree:   true,
			Origin:   map[string]interface{}{"region": "us-east-1", "zone": "us-east-1a", "id": 1., "meta": map[string]interface{}{"op": "create", "kl": 111., "x": []interface{}{2134., "csacsa", map[string]interface{}{"ss": true}}}},
		},
	}
	_, err := datainit.CreateBillingConfig(1, entity.BillingConfigType_DirectCustomer)
	assert.NoError(err)
	w := tests.PerformRequest(suite.router, "POST", "/tenants/1/billing_action_check", actionInfo)
	assert.Equal(http.StatusOK, w.Code)
	response := forms.BillingActionCheckResult{}
	err = json.Unmarshal(w.Body.Bytes(), &response)
	assert.NoError(err)
	assert.True(response.Pass)
	assert.Equal(actionInfo.Resource.Origin, response.Original)
	provider1 := forms.Provider_AWS
	batchInput := forms.BillingActionCheckBatchInput{
		Actions: []*forms.BillingActionInfo{
			{
				Action: forms.BillingAction_Create,
				Resource: forms.BillingResource{
					Type:     forms.BillingResourceType_DedicatedCluster,
					Provider: &provider,
					IsFree:   true,
				},
			},
			{
				Action: forms.BillingAction_View,
				Resource: forms.BillingResource{
					Type:     forms.BillingResourceType_DedicatedCluster,
					Provider: &provider1,
				},
			},
		},
	}
	w1 := tests.PerformRequest(suite.router, "POST", "/tenants/1/billing_action_check/_batch", batchInput)
	assert.Equal(http.StatusOK, w.Code)
	response1 := forms.BillingActionCheckBatchOutput{}
	err = json.Unmarshal(w1.Body.Bytes(), &response1)
	assert.NoError(err)
	assert.Len(response1.Results, 2)
	assert.True(response1.Results[0].Pass)
	assert.False(response1.Results[1].Pass)
}
