package test

import (
	"context"

	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

// MockDeployLBReconciler reconciles service object in test env
type MockDeployReconciler struct {
	client.Client
	Scheme *runtime.Scheme
}

func NewMockDeployReconciler(mgr ctrl.Manager) *MockDeployReconciler {
	return &MockDeployReconciler{
		Client: mgr.GetClient(),
		Scheme: mgr.GetScheme(),
	}
}

func (r *MockDeployReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	deploy := &appsv1.Deployment{}
	err := r.Get(ctx, req.NamespacedName, deploy)
	if err != nil {
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}
	if deploy.Spec.Selector.MatchLabels["app"] == "cdc-dns-forward" {
		deploy.Status.Conditions = make([]appsv1.DeploymentCondition, 0)
		deploy.Status.Conditions = append(deploy.Status.Conditions, appsv1.DeploymentCondition{
			Type:   appsv1.DeploymentAvailable,
			Status: corev1.ConditionTrue,
		})
	}
	return ctrl.Result{}, r.Client.Status().Update(ctx, deploy)
}

// SetupWithManager sets up the controller with the Manager.
func (r *MockDeployReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&appsv1.Deployment{}).
		Complete(r)
}
