package dataplane

import (
	"fmt"

	"github.com/tidbcloud/metrics-integration/global/internal/infrastructure/config"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
)

var restConfigs = make(map[string]*rest.Config)

// InitRestConfigs initializes the global RestConfigs map.
// Panic if any error occurs (should be called at process startup).
func InitRestConfigs(clusters []config.DataplaneCluster) {
	for _, cluster := range clusters {
		rc, err := buildRestConfig(cluster)
		if err != nil {
			panic(fmt.Errorf("failed to build rest.Config for %s: %w", cluster.Name, err))
		}
		restConfigs[cluster.Name] = rc
	}
}

func buildRestConfig(cluster config.DataplaneCluster) (*rest.Config, error) {
	switch cluster.Provider {
	case "local":
		return clientcmd.BuildConfigFromFlags("", cluster.ResourceID)
	case "incluster":
		return rest.InClusterConfig()
	case "aws":
		// TODO
		return nil, fmt.Errorf("aws provider not implemented")
	case "gke":
		// TODO
		return nil, fmt.Errorf("gke provider not implemented")
	default:
		return nil, fmt.Errorf("unknown provider: %s", cluster.Provider)
	}
}

// GetRestConfig returns the rest.Config for a given cluster name.
// If the cluster is not found, it falls back to using incluster config.
func GetRestConfig(name string) (*rest.Config, error) {
	rc, ok := restConfigs[name]
	if !ok {
		// Fallback to incluster config if cluster not found
		return rest.InClusterConfig()
	}
	return rc, nil
}
