package sdlc

import (
	"os"
	"testing"
)

func TestConfigRoundTrip(t *testing.T) {
	root := t.TempDir()

	if err := os.MkdirAll(SDLCRoot(root), 0o755); err != nil {
		t.Fatal(err)
	}

	original := DefaultConfig("test-project")

	if err := original.Save(root); err != nil {
		t.Fatalf("Save: %v", err)
	}

	loaded, err := LoadConfig(root)
	if err != nil {
		t.Fatalf("LoadConfig: %v", err)
	}

	if loaded.Version != 1 {
		t.Errorf("Version = %d, want 1", loaded.Version)
	}
	if loaded.Project.Name != "test-project" {
		t.Errorf("Project.Name = %q, want %q", loaded.Project.Name, "test-project")
	}
	if loaded.Branches.Main != "main" {
		t.Errorf("Branches.Main = %q, want main", loaded.Branches.Main)
	}
	if loaded.Branches.FeaturePrefix != "feature/" {
		t.Errorf("Branches.FeaturePrefix = %q, want feature/", loaded.Branches.FeaturePrefix)
	}
	if len(loaded.Phases.Enabled) != len(ValidPhases) {
		t.Errorf("Phases.Enabled len = %d, want %d", len(loaded.Phases.Enabled), len(ValidPhases))
	}
}

func TestDefaultConfigRequiredArtifacts(t *testing.T) {
	c := DefaultConfig("test")

	// specified phase requires spec
	arts, ok := c.Phases.RequiredArtifacts[PhaseSpecified]
	if !ok || len(arts) != 1 || arts[0] != ArtifactSpec {
		t.Errorf("RequiredArtifacts[specified] = %v, want [spec]", arts)
	}

	// planned phase requires 4 artifacts
	arts, ok = c.Phases.RequiredArtifacts[PhasePlanned]
	if !ok || len(arts) != 4 {
		t.Errorf("RequiredArtifacts[planned] len = %d, want 4", len(arts))
	}
}

func TestIsPhaseEnabled(t *testing.T) {
	c := DefaultConfig("test")

	if !c.IsPhaseEnabled(PhaseDraft) {
		t.Error("IsPhaseEnabled(draft) = false, want true")
	}
	if c.IsPhaseEnabled("bogus") {
		t.Error("IsPhaseEnabled(bogus) = true, want false")
	}
}

func TestLoadConfigNotInitialized(t *testing.T) {
	root := t.TempDir()
	_, err := LoadConfig(root)
	if err != ErrNotInitialized {
		t.Errorf("LoadConfig = %v, want ErrNotInitialized", err)
	}
}
