// Package svc provides service discovery for inter-service communication.
//
// Services discover sibling services via environment variables injected by the platform.
// When a component is deployed, it automatically receives env vars for all sibling services
// in the format: {COMPONENT_NAME}_URL (e.g., AUTH_SVC_URL, CHAT_SVC_URL).
//
// Usage:
//
//	// Get the URL of a sibling service
//	url := svc.ServiceURL("auth-svc")
//	if url == "" {
//	    // Service not available
//	}
//
//	// Or use the typed client
//	client, err := svc.NewClient("auth-svc")
//	if err != nil {
//	    // Handle error
//	}
//	resp, err := client.Get(ctx, "/users/123")
package svc

import (
	"os"
	"strings"
)

// ServiceURL returns the internal URL for a sibling service.
// The service name should be the component name as defined in the monorepo
// (e.g., "auth-svc", "chat-svc", "user-service").
//
// Returns empty string if the service is not configured (env var not set).
//
// Example:
//
//	url := svc.ServiceURL("auth-svc")  // Returns value of AUTH_SVC_URL
func ServiceURL(serviceName string) string {
	envKey := toEnvKey(serviceName) + "_URL"
	return os.Getenv(envKey)
}

// ServiceConfigured returns true if a service URL is configured.
// Use this to check for optional service dependencies.
func ServiceConfigured(serviceName string) bool {
	return ServiceURL(serviceName) != ""
}

// MustServiceURL returns the internal URL for a sibling service.
// Panics if the service is not configured. Use this for required dependencies
// during application initialization.
func MustServiceURL(serviceName string) string {
	url := ServiceURL(serviceName)
	if url == "" {
		panic("required service not configured: " + serviceName)
	}
	return url
}

// toEnvKey converts a service name to its environment variable name prefix.
// Example: "auth-svc" -> "AUTH_SVC"
func toEnvKey(serviceName string) string {
	// Replace hyphens with underscores and convert to uppercase
	return strings.ToUpper(strings.ReplaceAll(serviceName, "-", "_"))
}
