// Copyright 2024 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 framework

import (
	"context"

	"github.com/onsi/ginkgo/v2"
	"github.com/onsi/gomega"
	corev1 "k8s.io/api/core/v1"

	"github.com/pingcap/tidb-operator/apis/core/v1alpha1"
	"github.com/pingcap/tidb-operator/pkg/client"
	"github.com/pingcap/tidb-operator/tests/e2e/data"
	"github.com/pingcap/tidb-operator/tests/e2e/utils/waiter"
)

type Framework struct {
	Namespace *corev1.Namespace
	Cluster   *v1alpha1.Cluster

	Client client.Client
}

func New() *Framework {
	return &Framework{}
}

func (f *Framework) Setup() {
	// TODO: get context and config path from options
	c, err := newClient("", "")
	gomega.Expect(err).To(gomega.Succeed())
	f.Client = c

	ginkgo.BeforeEach(func(ctx context.Context) {
		ns := data.NewNamespace()

		f.Namespace = ns
		f.Cluster = data.NewCluster(ns.Name)

		gomega.Expect(
			f.Client.Create(ctx, f.Namespace),
		).To(gomega.Succeed())

		gomega.Expect(
			f.Client.Create(ctx, f.Cluster),
		).To(gomega.Succeed())

		ginkgo.DeferCleanup(func(ctx context.Context) {
			ginkgo.By("Delete the namespace")

			gomega.Expect(
				f.Client.Delete(ctx, f.Namespace),
			).To(gomega.Succeed())

			ginkgo.By("Ensure the namespace can be deleted")

			gomega.Expect(
				waiter.WaitForObjectDeleted(ctx, f.Client, f.Namespace, waiter.ShortTaskTimeout),
			).To(gomega.Succeed())
		})
	})
}

func (*Framework) Must(err error) {
	gomega.ExpectWithOffset(1, err).To(gomega.Succeed())
}

func (*Framework) True(b bool) {
	gomega.ExpectWithOffset(1, b).To(gomega.BeTrue())
}
