package infra

import (
	"fmt"
	"strings"
)

// GenerateTraefikDynamic genera el texto YAML de un traefik-dynamic.yml
// para el file provider de Traefik (Coolify).
// Replica el patron de apps/registry_api/traefik-dynamic.yml.
// Determinista: dado el mismo TraefikDynamicConfig siempre produce el mismo YAML.
func GenerateTraefikDynamic(cfg TraefikDynamicConfig) string {
	certResolver := cfg.CertResolver
	if certResolver == "" {
		certResolver = "letsencrypt"
	}

	// Build middleware lists
	httpsMiddlewares := []string{}
	if cfg.BasicAuthLine != "" {
		httpsMiddlewares = append(httpsMiddlewares, fmt.Sprintf("%s-auth", cfg.Name))
	}
	if cfg.EnableGzip {
		httpsMiddlewares = append(httpsMiddlewares, fmt.Sprintf("%s-gzip", cfg.Name))
	}

	var b strings.Builder

	fmt.Fprintf(&b, "http:\n")
	fmt.Fprintf(&b, "  routers:\n")

	// HTTP router (redirect only)
	fmt.Fprintf(&b, "    %s-http:\n", cfg.Name)
	fmt.Fprintf(&b, "      rule: \"Host(`%s`)\"\n", cfg.Domain)
	fmt.Fprintf(&b, "      entryPoints:\n")
	fmt.Fprintf(&b, "        - \"http\"\n")
	fmt.Fprintf(&b, "      middlewares:\n")
	fmt.Fprintf(&b, "        - \"%s-redirect\"\n", cfg.Name)
	fmt.Fprintf(&b, "      service: \"%s-service\"\n", cfg.Name)
	fmt.Fprintf(&b, "\n")

	// HTTPS router
	fmt.Fprintf(&b, "    %s-https:\n", cfg.Name)
	fmt.Fprintf(&b, "      rule: \"Host(`%s`)\"\n", cfg.Domain)
	fmt.Fprintf(&b, "      entryPoints:\n")
	fmt.Fprintf(&b, "        - \"https\"\n")
	if len(httpsMiddlewares) > 0 {
		fmt.Fprintf(&b, "      middlewares:\n")
		for _, mw := range httpsMiddlewares {
			fmt.Fprintf(&b, "        - \"%s\"\n", mw)
		}
	}
	fmt.Fprintf(&b, "      service: \"%s-service\"\n", cfg.Name)
	fmt.Fprintf(&b, "      tls:\n")
	fmt.Fprintf(&b, "        certResolver: %s\n", certResolver)
	fmt.Fprintf(&b, "\n")

	// Services
	fmt.Fprintf(&b, "  services:\n")
	fmt.Fprintf(&b, "    %s-service:\n", cfg.Name)
	fmt.Fprintf(&b, "      loadBalancer:\n")
	fmt.Fprintf(&b, "        servers:\n")
	fmt.Fprintf(&b, "          - url: \"%s\"\n", cfg.UpstreamURL)
	fmt.Fprintf(&b, "\n")

	// Middlewares
	fmt.Fprintf(&b, "  middlewares:\n")

	// redirect always present
	fmt.Fprintf(&b, "    %s-redirect:\n", cfg.Name)
	fmt.Fprintf(&b, "      redirectScheme:\n")
	fmt.Fprintf(&b, "        scheme: \"https\"\n")

	// auth only if BasicAuthLine provided
	if cfg.BasicAuthLine != "" {
		fmt.Fprintf(&b, "    %s-auth:\n", cfg.Name)
		fmt.Fprintf(&b, "      basicAuth:\n")
		fmt.Fprintf(&b, "        users:\n")
		fmt.Fprintf(&b, "          - \"%s\"\n", cfg.BasicAuthLine)
	}

	// gzip only if enabled
	if cfg.EnableGzip {
		fmt.Fprintf(&b, "    %s-gzip:\n", cfg.Name)
		fmt.Fprintf(&b, "      compress: true\n")
	}

	return b.String()
}
