// Copyright 2020-2026 Project Capsule Authors
// SPDX-License-Identifier: Apache-2.0

package resources

import (
	"fmt"

	"github.com/go-logr/logr"
	"sigs.k8s.io/controller-runtime/pkg/manager"

	"github.com/projectcapsule/capsule/internal/cache"
	"github.com/projectcapsule/capsule/internal/controllers/utils"
	"github.com/projectcapsule/capsule/internal/metrics"
	"github.com/projectcapsule/capsule/pkg/runtime/configuration"
)

func Add(
	log logr.Logger,
	mgr manager.Manager,
	configuration configuration.Configuration,
	opts utils.ControllerOptions,
	cache *cache.ImpersonationCache,
) (err error) {
	if err = (&NamespaceTrigger{
		log:           log.WithName("Global"),
		configuration: configuration,
		impersonation: cache,
	}).SetupWithManager(mgr, opts); err != nil {
		return fmt.Errorf("unable to create watcher controller: %w", err)
	}

	if err = (&globalResourceController{
		log:           log.WithName("Global"),
		configuration: configuration,
		metrics:       metrics.MustMakeGlobalTenantResourceRecorder(),

		impersonation: cache,
	}).SetupWithManager(mgr, opts); err != nil {
		return fmt.Errorf("unable to create global controller: %w", err)
	}

	if err = (&namespacedResourceController{
		log:           log.WithName("Namespaced"),
		configuration: configuration,
		metrics:       metrics.MustMakeTenantResourceRecorder(),

		impersonation: cache,
	}).SetupWithManager(mgr, opts); err != nil {
		return fmt.Errorf("unable to create namespaced controller: %w", err)
	}

	return nil
}
