package backup

import (
	"context"

	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/onsi/ginkgo"
	"github.com/onsi/gomega"
	"github.com/pingcap/tidb-operator/pkg/apis/pingcap/v1alpha1"
	"github.com/tidbcloud/shared-provider/tests/e2e/common/helper"
	"github.com/tidbcloud/shared-provider/tests/e2e/common/labels"
	"github.com/tidbcloud/shared-provider/tests/e2e/common/wait"
	"github.com/tidbcloud/shared-provider/tests/framework"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var _ = ginkgo.Describe("Backup", func() {
	f := framework.New()

	framework.It(labels.With(
		labels.TBackup,
	), "backup deletion", func() {
		ctx := context.Background()
		_, cluster, backup := helper.Create(ctx, f, helper.TypeBackup, true, "")

		err := f.InfraClient.Delete(ctx, cluster)
		gomega.Expect(err).NotTo(gomega.HaveOccurred())

		err = wait.WaitForObjectDeleted(ctx, f.InfraClient, cluster, helper.LongTaskTimeout)
		gomega.Expect(err).NotTo(gomega.HaveOccurred())

		err = f.InfraClient.Delete(ctx, backup)
		gomega.Expect(err).NotTo(gomega.HaveOccurred())

		s3Client := s3.NewFromConfig(f.AWSConfig)
		err = wait.WaitForS3DataCleaned(ctx, s3Client, backup.Status.BucketName, backup.Name, helper.DefaultTimeout)
		gomega.Expect(err).NotTo(gomega.HaveOccurred())
	})

	ginkgo.Context("Compatibility", func() {
		framework.It(labels.With(
			labels.TBackup,
			labels.FCompatibility,
			labels.From("release-0.5"),
		), "old backup can be cleaned", func() {
			ctx := context.Background()
			net, cluster, backup := helper.Create(ctx, f, helper.TypeBackup, true, "")

			err := f.InfraClient.Delete(ctx, cluster)
			gomega.Expect(err).NotTo(gomega.HaveOccurred())
			err = wait.WaitForObjectDeleted(ctx, f.InfraClient, cluster, helper.LongTaskTimeout)
			gomega.Expect(err).NotTo(gomega.HaveOccurred())

			// Upgrade to new manager.
			// NOTE(liubo02): It's not a real upgrade logic, so some display infos maybe wrong.
			// But it should be fine for business logic because all global resources(e.g. aws resources)
			// should be shared cross EKS in one region.
			// And tags.tidbcloud.com should be recoverable when reconciling.
			// TODO(liubo02): Upgrade by a more reasonable way
			f.ScheduleTo(ctx, net, framework.SuffixUpgrade)
			f.ScheduleTo(ctx, backup, framework.SuffixUpgrade)

			err = f.InfraClient.Delete(ctx, backup)
			gomega.Expect(err).NotTo(gomega.HaveOccurred())

			s3Client := s3.NewFromConfig(f.AWSConfig)
			err = wait.WaitForS3DataCleaned(ctx, s3Client, backup.Status.BucketName, backup.Name, helper.DefaultTimeout)
			gomega.Expect(err).NotTo(gomega.HaveOccurred())

			underlayBackup := v1alpha1.Backup{
				ObjectMeta: metav1.ObjectMeta{
					Name:      backup.Name,
					Namespace: backup.Namespace,
				},
			}
			err = wait.WaitForObjectDeleted(ctx, f.Client, &underlayBackup, helper.LongTaskTimeout)
			gomega.Expect(err).NotTo(gomega.HaveOccurred())
		})

	})
})
