package spindle

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"path/filepath"
	"testing"
)

func loadWorkflowFiles(t *testing.T, files int) error {
	t.Helper()
	src := newSourceRepo(t, "sha1")
	for i := range files {
		writeTestFile(t, filepath.Join(src, fmt.Sprintf(".tangled/workflows/w%03d.yaml", i)), "when: []\n")
	}
	commitEverything(t, src)
	sha := gitInDir(t, src, "rev-parse", "HEAD")
	_, _, err := (&Spindle{}).loadPipeline(context.Background(), src, filepath.Join(t.TempDir(), "checkout"), sha)
	return err
}

func TestLoadPipelineRefusesMoreWorkflowFilesThanItRuns(t *testing.T) {
	if err := loadWorkflowFiles(t, maxWorkflowFiles); err != nil {
		t.Fatalf("a repo with %d workflow files was refused: %v", maxWorkflowFiles, err)
	}
	if err := loadWorkflowFiles(t, maxWorkflowFiles+1); !errors.Is(err, errTooManyWorkflowFiles) {
		t.Fatalf("a repo with %d workflow files loaded with err = %v, want errTooManyWorkflowFiles", maxWorkflowFiles+1, err)
	}
}

func TestTooManyWorkflowFilesCarryAStatusTheKnotDrops(t *testing.T) {
	err := refusedAsStatus(fmt.Errorf("loading pipeline: %w", errTooManyWorkflowFiles))
	var coded interface{ HTTPStatus() int }
	if !errors.As(err, &coded) || coded.HTTPStatus() != http.StatusUnprocessableEntity {
		t.Fatalf("err = %v, want a 422", err)
	}
}
