package infra

import (
	"fmt"
	"strings"
)

// GenerateComposeTraefik genera el texto YAML de un docker-compose.yml
// para una app Go desplegada behind Traefik + Coolify.
// El output replica el patron de apps/registry_api/docker-compose.yml.
// Determinista: el orden de EnvVars sigue el orden de entrada.
func GenerateComposeTraefik(cfg ComposeTraefikConfig) string {
	var b strings.Builder

	// name
	fmt.Fprintf(&b, "name: %s\n\n", cfg.ProjectName)

	// services
	fmt.Fprintf(&b, "services:\n")
	fmt.Fprintf(&b, "  %s:\n", cfg.ServiceName)
	fmt.Fprintf(&b, "    build:\n")
	fmt.Fprintf(&b, "      context: %s\n", cfg.BuildContext)
	fmt.Fprintf(&b, "      dockerfile: %s\n", cfg.Dockerfile)
	fmt.Fprintf(&b, "    container_name: %s\n", cfg.ServiceName)
	fmt.Fprintf(&b, "    restart: unless-stopped\n")
	fmt.Fprintf(&b, "    ports:\n")
	fmt.Fprintf(&b, "      - \"%d:%d\"\n", cfg.Port, cfg.Port)

	if cfg.VolumeName != "" {
		fmt.Fprintf(&b, "    volumes:\n")
		fmt.Fprintf(&b, "      - %s:/data\n", cfg.VolumeName)
	}

	if len(cfg.EnvVars) > 0 {
		fmt.Fprintf(&b, "    environment:\n")
		for _, key := range cfg.EnvVars {
			fmt.Fprintf(&b, "      - %s=${%s:-}\n", key, key)
		}
	}

	fmt.Fprintf(&b, "    networks:\n")
	fmt.Fprintf(&b, "      - %s\n", cfg.Network)

	// volumes section
	if cfg.VolumeName != "" {
		fmt.Fprintf(&b, "\nvolumes:\n")
		fmt.Fprintf(&b, "  %s:\n", cfg.VolumeName)
	}

	// networks section
	fmt.Fprintf(&b, "\nnetworks:\n")
	fmt.Fprintf(&b, "  %s:\n", cfg.Network)
	fmt.Fprintf(&b, "    external: true\n")

	return b.String()
}
