package config

import (
	"path/filepath"
	"testing"
)

func TestLoad_DispatchHCL(t *testing.T) {
	p := writeTestFile(t, t.TempDir(), "config.hcl", exampleHCL)
	cfg, err := Load(p)
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if cfg.DBPath != "/tmp/orca/test.db" {
		t.Errorf("DBPath=%q", cfg.DBPath)
	}
	if cfg.NodeCapacity == nil || cfg.NodeCapacity.CPU != 4 {
		t.Errorf("NodeCapacity=%+v", cfg.NodeCapacity)
	}
}

func TestLoad_DispatchMarkdown(t *testing.T) {
	p := writeTestFile(t, t.TempDir(), "config.md", exampleMarkdown)
	cfg, err := Load(p)
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if cfg.DBPath != "/tmp/orca/test.db" {
		t.Errorf("DBPath=%q", cfg.DBPath)
	}
	if cfg.ListenAddr != "127.0.0.1:9999" {
		t.Errorf("ListenAddr=%q", cfg.ListenAddr)
	}
	if cfg.NodeCapacity == nil || cfg.NodeCapacity.CPU != 4 {
		t.Errorf("NodeCapacity=%+v", cfg.NodeCapacity)
	}
}

func TestLoad_DispatchYAML(t *testing.T) {
	body := "listen_addr: 0.0.0.0:5555\ndb_path: /bare.db\nnode_capacity:\n  cpu: 2\n  memory_mb: 4096\n"
	p := writeTestFile(t, t.TempDir(), "config.yaml", body)
	cfg, err := Load(p)
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if cfg.ListenAddr != "0.0.0.0:5555" {
		t.Errorf("ListenAddr=%q", cfg.ListenAddr)
	}
	if cfg.DBPath != "/bare.db" {
		t.Errorf("DBPath=%q", cfg.DBPath)
	}
	if cfg.NodeCapacity == nil || cfg.NodeCapacity.CPU != 2 {
		t.Errorf("NodeCapacity=%+v", cfg.NodeCapacity)
	}
}

func TestLoad_DispatchYML(t *testing.T) {
	body := "listen_addr: 1.2.3.4:9\n"
	p := writeTestFile(t, t.TempDir(), "config.yml", body)
	cfg, err := Load(p)
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if cfg.ListenAddr != "1.2.3.4:9" {
		t.Errorf("ListenAddr=%q", cfg.ListenAddr)
	}
}

func TestLoad_DispatchFirstExistingWins(t *testing.T) {
	dir := t.TempDir()
	missing := filepath.Join(dir, "missing.md")
	existing := writeTestFile(t, dir, "real.hcl", exampleHCL)
	cfg, err := Load(missing, existing)
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if cfg.DBPath != "/tmp/orca/test.db" {
		t.Errorf("DBPath=%q", cfg.DBPath)
	}
}

func TestLoad_DispatchMissingReturnsZero(t *testing.T) {
	cfg, err := Load(filepath.Join(t.TempDir(), "nope.md"))
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if cfg == nil {
		t.Fatal("nil config")
	}
	if cfg.DBPath != "" || cfg.ListenAddr != "" || cfg.NodeCapacity != nil {
		t.Errorf("expected zero config, got %+v", cfg)
	}
}

func TestLoad_DispatchHCLMalformed(t *testing.T) {
	p := writeTestFile(t, t.TempDir(), "bad.hcl", "db_path = ")
	if _, err := Load(p); err == nil {
		t.Fatal("expected error for malformed HCL")
	}
}

func TestLoad_DispatchUnknownExtFallsBackToHCL(t *testing.T) {
	p := writeTestFile(t, t.TempDir(), "config.unknown", exampleHCL)
	cfg, err := Load(p)
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if cfg.DBPath != "/tmp/orca/test.db" {
		t.Errorf("DBPath=%q", cfg.DBPath)
	}
}
