/*
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/predicate"

	eksv1alpha1 "github.com/tidbcloud/eks-provider/api/v1alpha1"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/task"
	mastermgr "github.com/tidbcloud/eks-provider/controllers/tiflow/task/master_mgr"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/task/master_mgr/gke"
	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	"github.com/tidbcloud/infra-provider/pkg/cloud/aws"
	"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/namer"
	"github.com/tidbcloud/infra-provider/pkg/procedure"
)

// TiflowClusterMasterManagerReconciler reconciles a TiflowClusterMasterManager object
type TiflowClusterMasterManagerReconciler struct {
	BaseTiflowReconciler

	awsCli aws.Client
}

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

//+kubebuilder:rbac:groups=eks.infra.pingcap.com,resources=tiflowclustermastermanagers,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=eks.infra.pingcap.com,resources=tiflowclustermastermanagers/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=eks.infra.pingcap.com,resources=tiflowclustermastermanagers/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 *TiflowClusterMasterManagerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	log := r.Logger.WithValues("object", req.NamespacedName)
	log.Info("Reconciling Tiflow Cluster Master Manager")
	start := time.Now()
	defer func() {
		metricsctrl.ReconcileDuration.
			WithLabelValues("tiflow_cluster_master_manager").Observe(time.Since(start).Seconds())
		log.Info("Finish tiflow cluster master manager reconcile", "take", time.Since(start))
	}()

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

	c, err := r.buildContext(ctx, tiflowClusterMasterManager)
	if err != nil {
		return ctrl.Result{}, err
	}

	tasks := r.buildTaskGroup(c)
	d := deploy.NewDeployer(tasks, nil, r.Logger)
	var res ctrl.Result
	if tiflowClusterMasterManager.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(tiflowClusterMasterManager, corev1.EventTypeNormal, "ReconcileSuccess", "")
	} else {
		r.EventRecorder.Event(tiflowClusterMasterManager, corev1.EventTypeWarning, "ReconcileFail", err.Error())
	}
	return res, err
}

func (r *TiflowClusterMasterManagerReconciler) buildContext(ctx context.Context, tiflowClusterMasterManager *eksv1alpha1.TiflowClusterMasterManager) (*mastermgr.Context, error) {
	network, err := r.QueryNetworkInfo(ctx, tiflowClusterMasterManager.Namespace, tiflowClusterMasterManager.Spec.NetworkName)
	if err != nil {
		return nil, err
	}

	_, err = r.CheckAndGetMasterSpecCode(ctx, network, r.Config.TiflowCluster.Master.DefaultSpecCode)
	if err != nil {
		return nil, err
	}

	var acct cloudv1.Account
	// FIXME(Huaxi): remove this check after the account scheduler is ready.
	if network.Spec.AccountRef != nil {
		if err := r.Cache.Get(ctx, types.NamespacedName{Name: network.Spec.AccountRef.Name}, &acct); err != nil {
			return nil, fmt.Errorf("unable to get account %s: %v", network.Spec.AccountRef.Name, err)
		}
	}
	c := (&mastermgr.Context{
		Local:  r.Local,
		Config: r.Config,
		Logger: r.Logger,

		TiflowClusterMasterManager: tiflowClusterMasterManager,
		Network:                    network,
		Account:                    &acct,
	}).Default()

	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")
	}

	tiflowClusterExecutorList, err := r.queryTiflowClusterExecutorList(ctx, tiflowClusterMasterManager.Namespace, c.Namer)
	if err != nil {
		return nil, err
	}
	c.TiflowClusterExecutorList = tiflowClusterExecutorList

	activeTiflowClusterMasterList, err := r.queryActiveTiflowClusterMasterList(ctx, tiflowClusterMasterManager.Namespace, c.Namer)
	if err != nil {
		return nil, err
	}
	c.ActiveTiflowClusterMasterList = activeTiflowClusterMasterList
	return c, nil
}

func (r *TiflowClusterMasterManagerReconciler) queryTiflowClusterExecutorList(
	ctx context.Context, namespace string, namer *namer.TiflowNamer) ([]eksv1alpha1.TiflowClusterExecutor, error) {
	tiflowClusterExecutorList := &eksv1alpha1.TiflowClusterExecutorList{}
	if err := r.Cache.List(ctx, tiflowClusterExecutorList,
		client.InNamespace(namespace),
		client.MatchingLabels(map[string]string{
			eksv1alpha1.TiflowMasterManagerTypeLabelKey: namer.GetTiflowClusterMasterManagerType(),
		}),
	); err != nil {
		return nil, fmt.Errorf("unable to list tiflow cluster executor in ns: %s: %v", namespace, err)
	}

	var executorList []eksv1alpha1.TiflowClusterExecutor
	for _, item := range tiflowClusterExecutorList.Items {
		if item.DeletionTimestamp.IsZero() && item.Spec.NetworkName == namer.GetNetworkName() {
			executorList = append(executorList, item)
		}
	}
	return executorList, nil
}

func (r *TiflowClusterMasterManagerReconciler) queryActiveTiflowClusterMasterList(
	ctx context.Context, namespace string, namer *namer.TiflowNamer) ([]eksv1alpha1.TiflowClusterMaster, error) {
	tiflowClusterMasterList := &eksv1alpha1.TiflowClusterMasterList{}
	if err := r.Cache.List(ctx, tiflowClusterMasterList,
		client.InNamespace(namespace),
		client.MatchingLabels(map[string]string{
			eksv1alpha1.TiflowMasterManagerLabelKey: namer.GetTiflowClusterMasterManagerName(),
		}),
	); err != nil {
		return nil, fmt.Errorf("unable to list tiflow cluster master in ns %s, label is %s:%s, : %v",
			namespace, eksv1alpha1.TiflowMasterManagerLabelKey, namer.GetTiflowClusterMasterManagerName(), err)
	}

	var activeList []eksv1alpha1.TiflowClusterMaster
	for _, item := range tiflowClusterMasterList.Items {
		if item.DeletionTimestamp.IsZero() && item.Spec.NetworkName == namer.GetNetworkName() {
			activeList = append(activeList, item)
		}
	}
	return activeList, nil
}

func (r *TiflowClusterMasterManagerReconciler) buildTaskGroup(c *mastermgr.Context) []deploy.Task {
	tasks := []deploy.Task{
		mastermgr.NewGuardian(c),
		mastermgr.NewNamespace(c),
		mastermgr.NewMasterDeployer(c),
		mastermgr.NewMasterDispatcher(c),
	}

	if r.Config.Predicate.MatchLabels[cloudv1.ProviderTypeLabel] == consts.ProviderTypeGKE {
		tasks = append(tasks, gke.NewRDSSecret(c))
	}

	tasks = append(tasks, mastermgr.NewO11yCluster(c))
	return tasks
}

func (r *TiflowClusterMasterManagerReconciler) updateCreate(ctx context.Context, t *mastermgr.Context, results []deploy.Result) (res ctrl.Result, err error) {
	res, err, _ = deploy.MinRequeue(results)
	if res.IsZero() || res.Requeue == false || res.RequeueAfter == 0 {
		res = ctrl.Result{
			RequeueAfter: time.Second * 10,
		}
	}
	if err := r.update(ctx, t.Local, t.TiflowClusterMasterManager); err != nil {
		return res, err
	}
	return
}

func (r *TiflowClusterMasterManagerReconciler) updateDelete(ctx context.Context, t *mastermgr.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)
	if err == nil && retriableErrs == nil {
		controllerutil.RemoveFinalizer(t.TiflowClusterMasterManager, task.Finalizer)
	}
	if err := r.update(ctx, t.Local, t.TiflowClusterMasterManager); err != nil {
		return res, err
	}
	return
}

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

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