// Copyright 2022 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package functionality

import (
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/pingcap/endless/pkg/matcher"
	. "github.com/pingcap/endless/pkg/workload"

	. "github.com/pingcap/endless/testcase/geopartition/utils"
)

func placementUnstableToScheduleTest(ctx *SuiteContext) {
	It("Unable to schedule #unable_to_schedule#", func() {
		defer func() {
			MustExec(ctx.DB, "DROP TABLE IF EXISTS t1,t2")
			MustExec(ctx.DB, "DROP PLACEMENT POLICY IF EXISTS p1")
			MustExec(ctx.DB, "DROP PLACEMENT POLICY IF EXISTS p2")
		}()
		MustExec(ctx.DB, "DROP TABLE IF EXISTS t1,t2")
		MustExec(ctx.DB, "DROP PLACEMENT POLICY IF EXISTS p1")
		MustExec(ctx.DB, "DROP PLACEMENT POLICY IF EXISTS p2")
		MustExec(ctx.DB, "CREATE PLACEMENT POLICY p1 PRIMARY_REGION=\"us-east-2\" REGIONS=\"us-east-1,us-east-2\" FOLLOWERS=4 SCHEDULE=\"EVEN\"")
		MustExec(ctx.DB, "CREATE PLACEMENT POLICY p2 PRIMARY_REGION=\"us-east-2\" REGIONS=\"us-east-1,us-east-2\" FOLLOWERS=4 SCHEDULE=\"MAJORITY_IN_PRIMARY\"")

		MustExec(ctx.DB, "CREATE TABLE t1(a int) PLACEMENT POLICY p1")
		MustExec(ctx.DB, "CREATE TABLE t2(a int) PLACEMENT POLICY p2")

		Try(WaitScheduledOrPending(ctx.DB, "t1", time.Minute))
		data := ReadAll(MustQuery(ctx.DB, "SHOW PLACEMENT FOR TABLE t1"))
		Expect(data[0][2]).To(Equal("PENDING"))

		Try(WaitScheduledOrPending(ctx.DB, "t2", time.Minute))
		data = ReadAll(MustQuery(ctx.DB, "SHOW PLACEMENT FOR TABLE t2"))
		Expect(data[0][2]).To(Equal("PENDING"))
	})
}
