package infra

import (
	"path/filepath"
	"testing"
)

func TestScanIssuesDir(t *testing.T) {
	root := registryRoot()
	issuesDir := filepath.Join(root, "dev", "issues")

	t.Run("scan devuelve al menos 90 issues", func(t *testing.T) {
		issues, err := ScanIssuesDir(issuesDir)
		if err != nil {
			t.Fatalf("ScanIssuesDir: %v", err)
		}
		if len(issues) < 90 {
			t.Errorf("expected >= 90 issues, got %d", len(issues))
		}
	})

	t.Run("issue 0130 esta presente", func(t *testing.T) {
		issues, err := ScanIssuesDir(issuesDir)
		if err != nil {
			t.Fatalf("ScanIssuesDir: %v", err)
		}
		found := false
		for _, iss := range issues {
			if iss.ID == "0130" {
				found = true
				break
			}
		}
		if !found {
			t.Error("issue 0130 not found in scan results")
		}
	})

	t.Run("issues ordenados por ID asc", func(t *testing.T) {
		issues, err := ScanIssuesDir(issuesDir)
		if err != nil {
			t.Fatalf("ScanIssuesDir: %v", err)
		}
		for i := 1; i < len(issues); i++ {
			if issues[i].ID < issues[i-1].ID {
				t.Errorf("not sorted at index %d: %q < %q", i, issues[i].ID, issues[i-1].ID)
				break
			}
		}
	})

	t.Run("completed issues tienen Completed=true", func(t *testing.T) {
		issues, err := ScanIssuesDir(issuesDir)
		if err != nil {
			t.Fatalf("ScanIssuesDir: %v", err)
		}
		completedCount := 0
		for _, iss := range issues {
			if iss.Completed {
				completedCount++
			}
		}
		if completedCount == 0 {
			t.Error("expected at least some completed issues")
		}
	})

	t.Run("directorio inexistente retorna error", func(t *testing.T) {
		_, err := ScanIssuesDir("/nonexistent/dev/issues")
		if err == nil {
			t.Error("expected error for nonexistent directory")
		}
	})
}
