package agent

import (
	"context"
	"fmt"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/remote_development/agent/k8s"
	rdutil "gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/remote_development/agent/util"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)

type sharedNamespaceHandler struct {
	k8sClient k8s.Client
}

func newSharedNamespaceHandler(k8sClient k8s.Client) *sharedNamespaceHandler {
	return &sharedNamespaceHandler{
		k8sClient: k8sClient,
	}
}

func (h *sharedNamespaceHandler) IsTerminated(_ context.Context, _ *WorkspaceRailsInfo, inventories []*unstructured.Unstructured) (bool, error) {
	return len(inventories) == 0, nil
}

func (h *sharedNamespaceHandler) Terminate(ctx context.Context, info *WorkspaceRailsInfo, inventories []*unstructured.Unstructured) <-chan *ErrorDetails {
	for _, inventory := range inventories {
		err := h.k8sClient.Delete(ctx, configMapGVR, inventory.GetNamespace(), inventory.GetName())
		if err != nil {
			return rdutil.ToAsync[*ErrorDetails](newErrorDetails(ErrorTypeKubernetes, fmt.Sprintf("failed to terminate workspace %s: %s", info.Name, err)))
		}
	}
	return nil
}

func (h *sharedNamespaceHandler) Create(context.Context, *WorkspaceRailsInfo) <-chan *ErrorDetails {
	return nil
}
