// /*
// Copyright 2025.
//
// 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 integration

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"testing"

	pcav1beta1 "github.com/cert-manager/aws-privateca-issuer/pkg/api/v1beta1"
	certmanagerv1 "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
	certmanagerv1alpha2 "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1alpha2"
	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	opv2alpha1 "github.com/pingcap/tidb-operator/api/v2/core/v1alpha1"
	cdcv1 "github.com/tidbcloud/ticdc-service-ng/api/v1"
	cdcctrl "github.com/tidbcloud/ticdc-service-ng/controllers/ticdc"
	"github.com/tidbcloud/ticdc-service-ng/pkg/config"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/envtest"
	logf "sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/log/zap"
	// +kubebuilder:scaffold:imports
)

// These tests use Ginkgo (BDD-style Go testing framework). Refer to
// http://onsi.github.io/ginkgo/ to learn more about Ginkgo.

var cfg *rest.Config
var k8sClient client.Client
var testEnv *envtest.Environment
var ctx context.Context
var cancel context.CancelFunc

const (
	kubeconfigPath = "./kubeconfig.tmp"
)

func TestControllers(t *testing.T) {
	RegisterFailHandler(Fail)

	RunSpecs(t, "Controller Suite")
}

var _ = BeforeSuite(func() {
	logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))

	ctx, cancel = context.WithCancel(context.TODO())

	By("bootstrapping test environment")
	testEnv = &envtest.Environment{
		CRDDirectoryPaths: []string{
			filepath.Join("..", "..", "config", "crd", "bases"),
			filepath.Join("../../../dataplane-manager/helm/tidb-operator-v2/v2.1.0-alpha.5"),
			filepath.Join("../", "external-crds"),
		},
		ErrorIfCRDPathMissing: true,

		// The BinaryAssetsDirectory is only required if you want to run the tests directly
		// without call the makefile target test. If not informed it will look for the
		// default path defined in controller-runtime which is /usr/local/kubebuilder/.
		// Note that you must have the required binaries setup under the bin directory to perform
		// the tests directly. When we run make test it will be setup and used automatically.
		BinaryAssetsDirectory: filepath.Join("..", "..", "bin", "k8s",
			fmt.Sprintf("1.31.0-%s-%s", runtime.GOOS, runtime.GOARCH)),
		// Use ControlPlane to enable storage.k8s.io/v1beta1
		ControlPlane: envtest.ControlPlane{
			APIServer: &envtest.APIServer{
				Args: []string{
					"--runtime-config=storage.k8s.io/v1beta1",
				},
			},
		},
	}

	var err error
	// cfg is defined in this file globally.
	cfg, err = testEnv.Start()
	Expect(err).NotTo(HaveOccurred())
	Expect(cfg).NotTo(BeNil())

	// save kubeconfig for troubleshooting
	data, err := getKubeconfig(cfg)
	Expect(err).NotTo(HaveOccurred())
	fname, err := filepath.Abs(kubeconfigPath)
	Expect(err).NotTo(HaveOccurred())
	err = os.WriteFile(fname, data, 0644) // #nosec G306
	Expect(err).NotTo(HaveOccurred())
	logf.Log.Info("write test kubeconfig", "filename", fname)

	utilruntime.Must(cdcv1.AddToScheme(scheme.Scheme))
	utilruntime.Must(opv2alpha1.Install(scheme.Scheme))
	utilruntime.Must(certmanagerv1.AddToScheme(scheme.Scheme))
	utilruntime.Must(pcav1beta1.AddToScheme(scheme.Scheme))
	utilruntime.Must(certmanagerv1alpha2.AddToScheme(scheme.Scheme))

	k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme})
	Expect(err).NotTo(HaveOccurred())
	Expect(k8sClient).NotTo(BeNil())

	conf := config.Config{
		Provider:          "aws",
		TiCDCBaseImage:    "gcr.io/pingcap-public/dbaas/ticdc",
		TiCDCPreStopImage: " gcr.io/pingcap-public/dbaas/ticdc/pre-stop:v1.2.3",
	}

	manager, err := ctrl.NewManager(cfg, ctrl.Options{Scheme: scheme.Scheme})
	Expect(err).NotTo(HaveOccurred())
	cdcReconciler := cdcctrl.TiCDCReconciler{
		Client:        manager.GetClient(),
		Cache:         manager.GetCache(),
		EventRecorder: manager.GetEventRecorderFor("ticdc"),
		RegionalCli:   &regionalClient{},
		Config:        &conf,
	}
	err = cdcReconciler.SetupWithManager(manager)
	Expect(err).NotTo(HaveOccurred())
	go func() {
		defer GinkgoRecover()
		err = manager.Start(ctx)
		Expect(err).ToNot(HaveOccurred())
	}()
})

var _ = AfterSuite(func() {
	By("tearing down the test environment")
	cancel()
	err := testEnv.Stop()
	Expect(err).NotTo(HaveOccurred())
})
