package test

import (
	"context"

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

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

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

func (r *MockServiceLBReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	svc := &corev1.Service{}
	err := r.Get(ctx, req.NamespacedName, svc)
	if err != nil {
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}
	if svc.Spec.Type == corev1.ServiceTypeLoadBalancer && svc.Status.LoadBalancer.Ingress == nil {
		svc.Status.LoadBalancer.Ingress = []corev1.LoadBalancerIngress{{
			Hostname: "dev.tidbcloud.com",
		}}
	}
	return ctrl.Result{}, r.Client.Status().Update(ctx, svc)
}

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