package deploy

import (
	"fmt"
	"os"
	"path/filepath"
)

// DeployConfig holds the configuration received from a NATS cmd.deploy command.
// These fields map directly to the Rust game server settings needed for initial deployment.
type DeployConfig struct {
	ServerName   string `json:"server_name"`
	MaxPlayers   int    `json:"max_players"`
	WorldSize    int    `json:"world_size"`
	Seed         int    `json:"seed"`
	ServerPort   int    `json:"server_port"`
	RconPort     int    `json:"rcon_port"`
	RconPassword string `json:"rcon_password"`
}

// DeployStatus represents a progress update published to NATS during deployment.
// The frontend listens on corrosion.{license_id}.deploy.status for these messages
// to display real-time deployment progress to the user.
type DeployStatus struct {
	Stage     string `json:"stage"`
	Progress  int    `json:"progress"`
	Message   string `json:"message"`
	Error     string `json:"error,omitempty"`
	Timestamp string `json:"timestamp"`
}

// Valid deployment stages:
//   downloading_steamcmd - Downloading and extracting SteamCMD
//   installing_steamcmd  - Running SteamCMD initial setup
//   downloading_rust     - Downloading Rust Dedicated Server via SteamCMD
//   configuring          - Generating server.cfg and identity directories
//   starting             - Launching the Rust server process
//   online               - Server is running and accepting connections
//   failed               - Deployment failed at some stage

// GenerateServerCfg creates the server.cfg file for a Rust Dedicated Server.
// It writes to {installDir}/server/server/corrosion/cfg/server.cfg, creating
// the full directory tree if it does not already exist.
func GenerateServerCfg(installDir string, cfg DeployConfig) error {
	cfgDir := filepath.Join(installDir, "server", "server", "corrosion", "cfg")

	if err := os.MkdirAll(cfgDir, 0755); err != nil {
		return fmt.Errorf("failed to create cfg directory %s: %w", cfgDir, err)
	}

	content := fmt.Sprintf(`server.hostname "%s"
server.maxplayers %d
server.worldsize %d
server.seed %d
server.port %d
rcon.port %d
rcon.password "%s"
rcon.web 1
server.identity "corrosion"
server.saveinterval 300
`, cfg.ServerName, cfg.MaxPlayers, cfg.WorldSize, cfg.Seed,
		cfg.ServerPort, cfg.RconPort, cfg.RconPassword)

	cfgPath := filepath.Join(cfgDir, "server.cfg")

	if err := os.WriteFile(cfgPath, []byte(content), 0644); err != nil {
		return fmt.Errorf("failed to write server.cfg to %s: %w", cfgPath, err)
	}

	return nil
}
