package core

import (
	"testing"
)

func TestParsePlan(t *testing.T) {
	plan := `# Plan de Ejecución Paralela

## Grupo 1

- Issue #0003 - testing agent
- Issue #0006 - improve db-reader

## Grupo 2

- Issue #0004 - api client — depende de #0003
`

	result := ParsePlan(plan)
	if result.IsErr() {
		t.Fatalf("ParsePlan failed: %v", result.Error())
	}

	ep := result.Unwrap()
	if len(ep.Groups) != 2 {
		t.Errorf("expected 2 groups, got %d", len(ep.Groups))
	}
	if ep.Total != 3 {
		t.Errorf("expected 3 total issues, got %d", ep.Total)
	}
	if ep.Groups[0].Issues[0].Number != 3 {
		t.Errorf("expected issue #0003, got #%04d", ep.Groups[0].Issues[0].Number)
	}
	if len(ep.Groups[1].Issues[0].Deps) != 1 || ep.Groups[1].Issues[0].Deps[0] != 3 {
		t.Errorf("expected issue #0004 to depend on #0003")
	}
}

func TestParsePlanEmpty(t *testing.T) {
	result := ParsePlan("")
	if !result.IsErr() {
		t.Error("expected error for empty plan")
	}
}

func TestFilterGroup(t *testing.T) {
	plan := ExecutionPlan{
		Groups: []IssueGroup{
			{Number: 1, Issues: []Issue{{Number: 1}}},
			{Number: 2, Issues: []Issue{{Number: 2}, {Number: 3}}},
		},
		Total: 3,
	}

	result := FilterGroup(plan, 2)
	if result.IsErr() {
		t.Fatalf("FilterGroup failed: %v", result.Error())
	}
	filtered := result.Unwrap()
	if filtered.Total != 2 {
		t.Errorf("expected 2 issues, got %d", filtered.Total)
	}
}

func TestFilterGroupNotFound(t *testing.T) {
	plan := ExecutionPlan{Groups: []IssueGroup{{Number: 1}}}
	result := FilterGroup(plan, 99)
	if !result.IsErr() {
		t.Error("expected error for non-existent group")
	}
}

func TestBuildWorktreeSpecs(t *testing.T) {
	issues := []Issue{
		{Number: 3, Slug: "0003-testing"},
		{Number: 6, Slug: "0006-db-reader"},
	}
	specs := BuildWorktreeSpecs(issues, "/tmp/project")
	if len(specs) != 2 {
		t.Fatalf("expected 2 specs, got %d", len(specs))
	}
	if specs[0].BranchName != "issue/0003-testing" {
		t.Errorf("expected branch issue/0003-testing, got %s", specs[0].BranchName)
	}
	if specs[1].WorkDir != "/tmp/project/worktrees/issue-0006" {
		t.Errorf("unexpected workdir: %s", specs[1].WorkDir)
	}
}
