// Package controller provides Kubernetes controllers for container-mom resources
package controller

import (
	"context"

	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"

	"github.com/pfeifferj/container-mom-go/pkg/apis/containermom/v1alpha1"
	momv1 "github.com/pfeifferj/container-mom-go/pkg/apis/containermom/v1alpha1"
)

// CustomerReconciler reconciles Customer resources
type CustomerReconciler struct {
	client.Client
	Scheme *runtime.Scheme
}

// Reconcile handles the reconciliation of Customer resources
func (r *CustomerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	logger := log.FromContext(ctx)

	customer := &momv1.Customer{}
	if err := r.Get(ctx, req.NamespacedName, customer); err != nil {
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}

	// Calculate current resource usage
	deployments := &momv1.ContainerMomDeploymentList{}
	if err := r.List(ctx, deployments, client.InNamespace(customer.Namespace)); err != nil {
		logger.Error(err, "failed to list deployments")
		return ctrl.Result{}, err
	}

	// Update resource usage
	usage := calculateResourceUsage(deployments.Items)
	customer.Status.UsedResources = v1alpha1.ResourceRequirements{
		CPU:    usage.CPU,
		Memory: usage.Memory,
	}

	// Check quota limits
	if err := r.enforceQuotas(ctx, customer); err != nil {
		logger.Error(err, "failed to enforce quotas")
		return ctrl.Result{}, err
	}

	// Update status
	if err := r.Status().Update(ctx, customer); err != nil {
		logger.Error(err, "failed to update customer status")
		return ctrl.Result{}, err
	}

	return ctrl.Result{}, nil
}

// SetupWithManager configures the controller with the Manager
func (r *CustomerReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&momv1.Customer{}).
		Complete(r)
}

func calculateResourceUsage(_ []momv1.ContainerMomDeployment) momv1.ResourceUsage {
	// Calculate total resource usage from deployments
	return momv1.ResourceUsage{}
}

func (r *CustomerReconciler) enforceQuotas(_ context.Context, _ *momv1.Customer) error {
	// Implement quota enforcement logic
	return nil
}
