package plan

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

	"metis/pkg/inventory"
)

func TestBuildIncludesInjectWhenEnvSet(t *testing.T) {
	defer os.Unsetenv("METIS_BOOT_PATH")
	os.Setenv("METIS_BOOT_PATH", "/mnt/boot")
	inv := &inventory.Inventory{
		Classes: []inventory.NodeClass{{
			Name:  "c1",
			Image: "file:///tmp/dummy",
		}},
		Nodes: []inventory.NodeSpec{{
			Name:     "n1",
			Class:    "c1",
			Hostname: "n1",
			IP:       "10.0.0.1",
			K3sRole:  "agent",
		}},
	}
	p, err := Build(inv, "n1", "/dev/sdz", "/tmp/cache")
	if err != nil {
		t.Fatalf("build: %v", err)
	}
	found := false
	for _, a := range p.Actions {
		if a.Type == "inject" {
			found = true
		}
	}
	if !found {
		t.Fatalf("expected inject action when METIS_BOOT_PATH set")
	}
}

func TestBuildAndExecuteErrorBranches(t *testing.T) {
	inv := &inventory.Inventory{}
	if _, err := Build(inv, "missing", "/dev/sdz", "/tmp/cache"); err == nil {
		t.Fatal("expected Build to fail for missing node")
	}
	if got := checksumFromInventory(inv, "missing"); got != "" {
		t.Fatalf("checksumFromInventory missing node = %q", got)
	}

	dir := t.TempDir()
	raw := filepath.Join(dir, "base.img")
	if err := os.WriteFile(raw, []byte("image"), 0o644); err != nil {
		t.Fatal(err)
	}
	sum := imageChecksum(t, raw)
	inv = &inventory.Inventory{
		Classes: []inventory.NodeClass{{
			Name:     "c1",
			Arch:     "arm64",
			OS:       "linux",
			Image:    "file://" + raw,
			Checksum: sum,
		}},
		Nodes: []inventory.NodeSpec{{
			Name:     "n1",
			Class:    "c1",
			Hostname: "n1",
			IP:       "10.0.0.1",
			K3sRole:  "agent",
		}},
	}
	if _, err := Execute(inv, "n1", "/dev/sdX", filepath.Join(dir, "cache"), true); err == nil {
		t.Fatal("expected placeholder device rejection")
	}
}
