package operator

import (
	"context"
	"fmt"

	v1alpha1 "github.com/pfeifferj/container-mom-go/pkg/apis/containermom/v1alpha1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

type DeploymentReconciler struct {
	client client.Client
}

func NewDeploymentReconciler(client client.Client) *DeploymentReconciler {
	return &DeploymentReconciler{
		client: client,
	}
}

func (r *DeploymentReconciler) reconcileDeployment(ctx context.Context, deployment *v1alpha1.ContainerMomDeployment) error {
	// Check if deployment exists
	existing := &v1alpha1.ContainerMomDeployment{}
	err := r.client.Get(ctx, types.NamespacedName{
		Name:      deployment.Name,
		Namespace: deployment.Namespace,
	}, existing)

	if err != nil {
		if client.IgnoreNotFound(err) != nil {
			return fmt.Errorf("failed to get deployment: %w", err)
		}
		// Create new deployment
		if err := r.client.Create(ctx, deployment); err != nil {
			return fmt.Errorf("failed to create deployment: %w", err)
		}
		return nil
	}

	// Update existing deployment
	existing.Spec = deployment.Spec
	if err := r.client.Update(ctx, existing); err != nil {
		return fmt.Errorf("failed to update deployment: %w", err)
	}

	return nil
}

func (r *DeploymentReconciler) deleteDeployment(ctx context.Context, name string) error {
	deployment := &v1alpha1.ContainerMomDeployment{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: "default", // Or use a namespace strategy
		},
	}
	if err := r.client.Delete(ctx, deployment); err != nil {
		return client.IgnoreNotFound(err)
	}
	return nil
}

func (r *DeploymentReconciler) listExistingDeployments(ctx context.Context) ([]v1alpha1.ContainerMomDeployment, error) {
	var list v1alpha1.ContainerMomDeploymentList
	if err := r.client.List(ctx, &list); err != nil {
		return nil, fmt.Errorf("failed to list deployments: %w", err)
	}
	return list.Items, nil
}
