package deploy

import (
	"fmt"
	"os"

	"crypto-miner-agent/config"
)

// Uninstall removes persistence, stops the process, and deletes the install directory.
func Uninstall(cfg config.RuntimeConfig) error {
	installDir, err := cfg.InstallDirectory()
	if err != nil {
		return err
	}
	installedBin, err := InstalledBinaryPath(cfg)
	if err != nil {
		return err
	}

	killWorkerProcess(cfg)
	removePersistence(cfg)
	RemoveFirewallExclusion(cfg)

	if path, err := CurrentExecutable(); err == nil && samePath(path, installedBin) {
		selfUninstallSpawn(installDir)
		os.Exit(0)
	}

	if err := os.RemoveAll(installDir); err != nil {
		return fmt.Errorf("remove install dir: %w", err)
	}
	os.Exit(0)
	return nil
}

// EnsureFirewallExclusion is implemented per platform.
func EnsureFirewallExclusion(cfg config.RuntimeConfig, binPath string) {
	if !cfg.FirewallExclusion {
		return
	}
	platformEnsureFirewall(cfg, binPath)
}

// RemoveFirewallExclusion is implemented per platform.
func RemoveFirewallExclusion(cfg config.RuntimeConfig) {
	platformRemoveFirewall(cfg)
}
