package builder

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

	"crypto-miner-server/internal/db"
)

func TestNewHandlerResolvesPaths(t *testing.T) {
	d, err := db.New(t.TempDir())
	if err != nil {
		t.Fatal(err)
	}
	defer d.Close()
	h := NewHandler(d, t.TempDir(), t.TempDir(), t.TempDir())
	if h.goBinPath == "" {
		t.Fatal("goBinPath should be set")
	}
}

func TestCopyFileRoundTrip(t *testing.T) {
	dir := t.TempDir()
	src := filepath.Join(dir, "src.txt")
	dst := filepath.Join(dir, "sub", "dst.txt")
	if err := os.WriteFile(src, []byte("hello"), 0644); err != nil {
		t.Fatal(err)
	}
	if err := copyFile(src, dst); err != nil {
		t.Fatal(err)
	}
	got, err := os.ReadFile(dst)
	if err != nil {
		t.Fatal(err)
	}
	if string(got) != "hello" {
		t.Fatalf("copy mismatch: %q", got)
	}
}

func TestCopyFileMissingSource(t *testing.T) {
	err := copyFile(filepath.Join(t.TempDir(), "missing"), filepath.Join(t.TempDir(), "out"))
	if err == nil {
		t.Fatal("expected error for missing source")
	}
}

func TestSetFleetSecretAndPolicy(t *testing.T) {
	h := &Handler{}
	h.SetFleetSecret("secret-123")
	if h.fleetSecret != "secret-123" {
		t.Fatal("fleet secret not stored")
	}
	h.SetBuildPolicy(BuildPolicy{DefaultObfuscate: true})
	if !h.policy.DefaultObfuscate {
		t.Fatal("policy not stored")
	}
}
