package tests

import (
	"encoding/json"
	"fmt"
	"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/db/entity"
	"github.com/pingcap/dbaas/billing2/forms"
	"github.com/pingcap/dbaas/billing2/model/billing"
	"github.com/pingcap/dbaas/billing2/utils/ginutils"
	"github.com/pingcap/dbaas/billing2/utils/tests"
	"github.com/pingcap/dbaas/billing2/utils/tests/datainit"
	"github.com/shopspring/decimal"
	"github.com/stretchr/testify/suite"
)

// func TestMain(m *testing.M) {
// 	testsetup.TestMain(m)
// }

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

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

func TestPackageSuite(t *testing.T) {
	suite.Run(t, new(PackageTestSuite))
}

var packageModel = &billing.PackageModel{}
var bindedPackageModel = &billing.BindedPackageModel{}

func (suite *PackageTestSuite) TestGetPackage() {
	assert := suite.Assert()
	info, _ := packageModel.CreatePackage(&forms.PackageInfo{})
	w := tests.PerformGetRequest(suite.router, fmt.Sprintf("/packages/%v", info.PackageID))
	assert.Equal(http.StatusNotFound, w.Code)

}

type PartialPackageSchema struct {
	Discount decimal.Decimal `json:"discount"`
}

func (suite *PackageTestSuite) TestPartialUpdatePackage() {
	assert := suite.Assert()
	config.Get().Set(config.APISwitchUpdateUnit, true)
	info, _ := packageModel.CreatePackage(&forms.PackageInfo{
		Description: "ABC",
	})
	w := tests.PerformRequest(suite.router, "PATCH", fmt.Sprintf("/packages/%d", info.PackageID), &PartialPackageSchema{Discount: decimal.NewFromInt(1)})
	assert.Equal(http.StatusOK, w.Code)
	res, err := packageModel.GetPackage(info.PackageID)
	assert.NoError(err)
	assert.Equal(res.Description, "ABC")
	assert.Equal(res.Discount, decimal.NewFromInt(1))
}

func (suite *PackageTestSuite) TestGetAllBindPackages() {
	assert := suite.Assert()
	datainit.CreateBillingConfig(1, entity.BillingConfigType_DirectCustomer)

	info, _ := packageModel.CreatePackage(&forms.PackageInfo{})
	bindedPackageModel.BindPackage(uint(1), info.PackageID)
	w := tests.PerformGetRequest(suite.router, "/tenants/1/binded_packages")
	assert.Equal(http.StatusOK, w.Code)
	ret := []forms.BindedPackageInfo{}
	err := json.NewDecoder(w.Body).Decode(&ret)
	assert.NoError(err)
}
