package server

import (
	"context"
	"log/slog"
	"net"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/kubernetes_api"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/logz"
)

type module struct {
	log      *slog.Logger
	proxy    kubernetesAPIProxy
	listener func(context.Context) (net.Listener, error)
}

func (m *module) Run(ctx context.Context) error {
	lis, err := m.listener(ctx)
	if err != nil {
		return err
	}
	// Error is ignored because kubernetesAPIProxy.Run() closes the listener and
	// a second close always produces an error.
	defer lis.Close() //nolint:errcheck

	m.log.Info("Kubernetes API endpoint is up",
		logz.NetNetworkFromAddr(lis.Addr()),
		logz.NetAddressFromAddr(lis.Addr()),
	)
	return m.proxy.Run(ctx, lis)
}

func (m *module) Name() string {
	return kubernetes_api.ModuleName
}
