package infra

import (
	"fmt"
	"sort"
	"strings"
)

// SystemdGenerateUnit genera el texto de un archivo .service de systemd.
func SystemdGenerateUnit(name, execStart, workDir, user string, env map[string]string) string {
	var b strings.Builder

	b.WriteString("[Unit]\n")
	b.WriteString(fmt.Sprintf("Description=%s\n", name))
	b.WriteString("After=network.target\n\n")

	b.WriteString("[Service]\n")
	b.WriteString("Type=simple\n")
	b.WriteString(fmt.Sprintf("ExecStart=%s\n", execStart))
	if workDir != "" {
		b.WriteString(fmt.Sprintf("WorkingDirectory=%s\n", workDir))
	}
	if user != "" {
		b.WriteString(fmt.Sprintf("User=%s\n", user))
	}

	// Environment vars en orden determinista
	if len(env) > 0 {
		keys := make([]string, 0, len(env))
		for k := range env {
			keys = append(keys, k)
		}
		sort.Strings(keys)
		for _, k := range keys {
			b.WriteString(fmt.Sprintf("Environment=%s=%s\n", k, env[k]))
		}
	}

	b.WriteString("Restart=on-failure\n")
	b.WriteString("RestartSec=5\n\n")

	b.WriteString("[Install]\n")
	b.WriteString("WantedBy=multi-user.target\n")

	return b.String()
}
