/*
Copyright 2021.

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 tiflow

import (
	"context"
	"fmt"
	"time"

	corev1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/types"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/builder"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/controller"
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
	"sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/predicate"

	eksv1alpha1 "github.com/tidbcloud/eks-provider/api/v1alpha1"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/config/component"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/spec"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/task"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/task/cluster"
	clustereks "github.com/tidbcloud/eks-provider/controllers/tiflow/task/cluster/eks"
	clustergke "github.com/tidbcloud/eks-provider/controllers/tiflow/task/cluster/gke"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/task/cluster/master"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/task/cluster/master/eks"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/task/cluster/master/gke"
	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	"github.com/tidbcloud/infra-provider/pkg/cloud/gcp"
	"github.com/tidbcloud/infra-provider/pkg/config"
	"github.com/tidbcloud/infra-provider/pkg/consts"
	"github.com/tidbcloud/infra-provider/pkg/controllers/common"
	"github.com/tidbcloud/infra-provider/pkg/deploy"
	metricsctrl "github.com/tidbcloud/infra-provider/pkg/metrics/controller"
	"github.com/tidbcloud/infra-provider/pkg/procedure"
)

// TiflowClusterMasterReconciler reconciles a TiflowClusterMaster object
type TiflowClusterMasterReconciler struct {
	BaseTiflowReconciler
}

func NewTiflowClusterMasterReconciler(mgr ctrl.Manager, infraCli client.Client, infraReader client.Reader, config config.RootConfig, svc procedure.AWSService, gcpCli gcp.Client) *TiflowClusterMasterReconciler {
	tiflowClusterMasterReconciler := &TiflowClusterMasterReconciler{
		BaseTiflowReconciler: BaseTiflowReconciler{
			Scheme:        mgr.GetScheme(),
			Local:         infraCli,
			Logger:        ctrl.Log.WithName("controllers").WithName("TiflowClusterMaster"),
			Config:        config,
			Cache:         infraReader,
			EventRecorder: mgr.GetEventRecorderFor("tiflow-cluster-master-controller"),
			AWSSVC:        svc,
			GCP:           gcpCli,
		},
	}
	return tiflowClusterMasterReconciler
}

//+kubebuilder:rbac:groups=eks.infra.pingcap.com,resources=tiflowclustermasters,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=eks.infra.pingcap.com,resources=tiflowclustermasters/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=eks.infra.pingcap.com,resources=tiflowclustermasters/finalizers,verbs=update

// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.12.2/pkg/reconcile
func (r *TiflowClusterMasterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	log := r.Logger.WithValues("object", req.NamespacedName)
	log.Info("Reconciling Tiflow Cluster Master")
	start := time.Now()
	defer func() {
		metricsctrl.ReconcileDuration.
			WithLabelValues("tiflow_cluster_master").Observe(time.Since(start).Seconds())
		log.Info("Finish tiflow cluster master reconcile", "take", time.Since(start))
	}()

	tiflowClusterMaster := &eksv1alpha1.TiflowClusterMaster{}
	if err := r.Cache.Get(ctx, req.NamespacedName, tiflowClusterMaster); err != nil {
		if apierrors.IsNotFound(err) {
			return ctrl.Result{}, nil
		}
		return ctrl.Result{}, fmt.Errorf("unable to get tiflow cluster master %s: %v", req.NamespacedName, err)
	}

	c, err := r.buildContext(ctx, tiflowClusterMaster)
	if err != nil {
		r.Logger.Error(err, "unable to build context for tiflow cluster master", "name", req.NamespacedName)
		return ctrl.Result{RequeueAfter: time.Minute * 1}, nil
	}

	tasks := r.buildTaskGroup(c)
	d := deploy.NewDeployer(tasks, nil, r.Logger)
	var res ctrl.Result
	if tiflowClusterMaster.DeletionTimestamp.IsZero() {
		res, err = r.updateCreate(ctx, c, d.Deploy(ctx))
	} else {
		res, err = r.updateDelete(ctx, c, d.Destroy(ctx))
	}

	if err == nil {
		r.EventRecorder.Event(tiflowClusterMaster, corev1.EventTypeNormal, "ReconcileSuccess", "")
	} else {
		r.EventRecorder.Event(tiflowClusterMaster, corev1.EventTypeWarning, "ReconcileFail", err.Error())
	}
	return res, err
}

func (r *TiflowClusterMasterReconciler) buildContext(
	ctx context.Context, tiflowClusterMaster *eksv1alpha1.TiflowClusterMaster) (*master.Context, error) {
	network, err := r.QueryNetworkInfo(ctx, tiflowClusterMaster.Namespace, tiflowClusterMaster.Spec.NetworkName)
	if err != nil {
		return nil, err
	}

	provider, err := r.QueryProvider(ctx, network.Spec.Provider)
	if err != nil {
		return nil, err
	}

	tiflowSpec, err := r.CheckAndGetMasterSpecCode(ctx, network, tiflowClusterMaster.Spec.SpecCode)
	if err != nil {
		return nil, err
	}

	c := (&master.Context{
		BaseContext: &cluster.BaseContext{
			Local:      r.Local,
			Config:     r.Config,
			Network:    network,
			Logger:     r.Logger,
			TiflowSpec: tiflowSpec,
			Provider:   provider,
			AWSSVC:     r.AWSSVC,
			GCP:        r.GCP,
		},
		TiflowClusterMaster: tiflowClusterMaster,
	}).Default()

	// NOTE: if we meet error here, DON'T return error
	// leave the tiflowclustermaster task reports this error
	cc, err := component.NewMasterConfigQuirer(c).Execute(ctx)
	if err == nil {
		c.ClusterConfig = cc
	} else {
		r.Logger.Error(err, "get master config error")
	}

	err = c.SetRemoteClient(ctx)
	if err != nil {
		// DON'T return error here, or it will block the deletion of object
		// If we get any error here, tasks will report error since the default
		// getter is an empty getter
		r.Logger.Error(err, "fail to set remote client")
	}

	return c, nil
}

func (r *TiflowClusterMasterReconciler) buildTaskGroup(c *master.Context) []deploy.Task {
	tiDBClusterName := spec.GetTiDBClusterName(&c.TiflowClusterMaster.ObjectMeta)
	objCond := &c.TiflowClusterMaster.Status.Conditions
	if r.Config.Predicate.MatchLabels[cloudv1.ProviderTypeLabel] == consts.ProviderTypeGKE {
		// gke provider
		return []deploy.Task{
			master.NewGuardian(c),
			gke.NewBucket(c),
			// right now we use public-ip to access engine metadb, so no private-link related task
			clustergke.NewNodePool(c.BaseContext, tiDBClusterName, objCond),
			gke.NewTiflowClusterMaster(c),
			clustergke.NewNodeGroupGC(c.BaseContext, objCond),
		}
	}

	// eks provider
	return []deploy.Task{
		master.NewGuardian(c),
		eks.NewBucket(c),
		eks.NewPrivateLinkEndpoint(c),
		clustereks.NewNodeGroup(c.BaseContext, tiDBClusterName, objCond),
		eks.NewTiflowClusterMaster(c),
		clustereks.NewNodeGroupGC(c.BaseContext, objCond),
	}
}

func (r *TiflowClusterMasterReconciler) updateCreate(ctx context.Context, t *master.Context, results []deploy.Result) (res ctrl.Result, err error) {
	res, err, retriableErrs := deploy.MinRequeue(results)
	switch phase := t.TiflowClusterMaster.Status.Phase; phase {
	case eksv1alpha1.TiflowClusterMasterPhaseCreating:
		if err == nil && retriableErrs == nil {
			log.FromContext(ctx).Info("mark tiflow cluster master become running when creating cluster",
				"sinceCreate", time.Since(t.TiflowClusterMaster.CreationTimestamp.Time))
			t.TiflowClusterMaster.Status.Phase = eksv1alpha1.TiflowClusterMasterPhaseRunning
		}
	default:
	}
	if err := r.update(ctx, t.Local, t.TiflowClusterMaster); err != nil {
		return res, err
	}
	return
}

func (r *TiflowClusterMasterReconciler) updateDelete(ctx context.Context, t *master.Context, results []deploy.Result) (res ctrl.Result, err error) {
	// If the cluster is pending delete, then the deletion tasks are not actually performed
	res, err, retriableErrs := deploy.MinRequeue(results)
	switch phase := t.TiflowClusterMaster.Status.Phase; phase {
	case eksv1alpha1.TiflowClusterMasterPhaseDeleting:
		if err == nil && retriableErrs == nil {
			controllerutil.RemoveFinalizer(t.TiflowClusterMaster, task.Finalizer)
		}
	default:
	}
	if err := r.update(ctx, t.Local, t.TiflowClusterMaster); err != nil {
		return res, err
	}
	return
}

func (r *TiflowClusterMasterReconciler) update(ctx context.Context, cli client.Client, tiflowClusterMaster *eksv1alpha1.TiflowClusterMaster) error {
	tiflowClusterStatus := tiflowClusterMaster.Status.DeepCopy()
	if err := cli.Update(ctx, tiflowClusterMaster); err != nil {
		return err
	}
	if err := cli.Get(ctx, types.NamespacedName{Name: tiflowClusterMaster.Name, Namespace: tiflowClusterMaster.Namespace}, tiflowClusterMaster); err != nil {
		return err
	}
	tiflowClusterMaster.Status = *tiflowClusterStatus
	return cli.Status().Update(ctx, tiflowClusterMaster)
}

// SetupWithManager sets up the controller with the Manager.
func (r *TiflowClusterMasterReconciler) SetupWithManager(mgr ctrl.Manager, p ...predicate.Predicate) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&eksv1alpha1.TiflowClusterMaster{}, builder.WithPredicates(p...)).
		WithOptions(controller.Options{RateLimiter: common.DefaultRateLimiter(), MaxConcurrentReconciles: 10}).
		Complete(r)
}
