package repo

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/gitlink-org/gitlink-cli/internal/client"
	"github.com/gitlink-org/gitlink-cli/shortcuts/common"
)

// ---- helpers ----

func findShortcut(t *testing.T, name string) *common.Shortcut {
	t.Helper()
	for _, s := range Shortcuts() {
		if s.Name == name {
			return s
		}
	}
	t.Fatalf("shortcut %q not found", name)
	return nil
}

func runBatchCreateShortcut(t *testing.T, server *httptest.Server, args map[string]string) error {
	t.Helper()
	s := findShortcut(t, "batch-create")
	ctx := &common.RuntimeContext{
		Client: &client.Client{HTTP: server.Client(), BaseURL: server.URL},
		Owner:  "owner",
		Repo:   "repo",
		Format: "json",
		Args:   args,
	}
	return s.Run(ctx)
}

func runBatchUpdateShortcut(t *testing.T, server *httptest.Server, args map[string]string) error {
	t.Helper()
	s := findShortcut(t, "batch-update")
	ctx := &common.RuntimeContext{
		Client: &client.Client{HTTP: server.Client(), BaseURL: server.URL},
		Owner:  "owner",
		Repo:   "repo",
		Format: "json",
		Args:   args,
	}
	return s.Run(ctx)
}

func writeJSONResp(t *testing.T, w http.ResponseWriter, v interface{}) {
	t.Helper()
	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(v); err != nil {
		t.Fatalf("writeJSON: %v", err)
	}
}

func decodeReqBody(t *testing.T, r *http.Request) map[string]interface{} {
	t.Helper()
	var payload map[string]interface{}
	if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
		t.Fatalf("decode body: %v", err)
	}
	return payload
}

func writeTempCSV(t *testing.T, content string) string {
	t.Helper()
	path := filepath.Join(t.TempDir(), "repos.csv")
	if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
		t.Fatalf("write temp csv: %v", err)
	}
	return path
}

// ---- runBatchCreate tests ----

func TestBatchCreate_DryRun(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		t.Fatalf("no API calls expected in dry-run mode, got %s %s", r.Method, r.URL.Path)
	}))
	defer server.Close()

	err := runBatchCreateShortcut(t, server, map[string]string{
		"names":   "repo1,repo2",
		"dry-run": "true",
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}

func TestBatchCreate_FromNames(t *testing.T) {
	var createdBodies []map[string]interface{}
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.Method == "GET" && r.URL.Path == "/users/me.json":
			writeJSONResp(t, w, map[string]interface{}{
				"login":   "testuser",
				"user_id": float64(42),
			})
		case r.Method == "POST" && strings.HasPrefix(r.URL.Path, "/testuser/"):
			createdBodies = append(createdBodies, decodeReqBody(t, r))
			writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
		default:
			t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
		}
	}))
	defer server.Close()

	err := runBatchCreateShortcut(t, server, map[string]string{
		"names": "repo-a,repo-b",
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(createdBodies) != 2 {
		t.Fatalf("expected 2 API calls, got %d", len(createdBodies))
	}
	if createdBodies[0]["name"] != "repo-a" {
		t.Fatalf("first name: got %q, want %q", createdBodies[0]["name"], "repo-a")
	}
	if createdBodies[1]["name"] != "repo-b" {
		t.Fatalf("second name: got %q, want %q", createdBodies[1]["name"], "repo-b")
	}
	for _, body := range createdBodies {
		if body["repository_name"] != body["name"] {
			t.Fatalf("repository_name should match name: %v vs %v", body["repository_name"], body["name"])
		}
		if body["user_id"] != float64(42) {
			t.Fatalf("user_id: got %v, want 42", body["user_id"])
		}
	}
}

func TestBatchCreate_NoNames(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
	}))
	defer server.Close()

	err := runBatchCreateShortcut(t, server, map[string]string{})
	if err == nil {
		t.Fatal("expected error, got nil")
	}
}

func TestBatchCreate_NoNamesDryRun(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
	}))
	defer server.Close()

	err := runBatchCreateShortcut(t, server, map[string]string{"dry-run": "true"})
	if err == nil {
		t.Fatal("expected error for no names even in dry-run, got nil")
	}
}

func TestBatchCreate_WithPrivate(t *testing.T) {
	var createdBody map[string]interface{}
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.Method == "GET" && r.URL.Path == "/users/me.json":
			writeJSONResp(t, w, map[string]interface{}{
				"login":   "testuser",
				"user_id": float64(42),
			})
		case r.Method == "POST":
			createdBody = decodeReqBody(t, r)
			writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
		default:
			t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
		}
	}))
	defer server.Close()

	err := runBatchCreateShortcut(t, server, map[string]string{
		"names":   "private-repo",
		"private": "true",
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if createdBody["private"] != true {
		t.Fatalf("private: got %v, want true", createdBody["private"])
	}
}

func TestBatchCreate_WithDescription(t *testing.T) {
	var createdBody map[string]interface{}
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.Method == "GET" && r.URL.Path == "/users/me.json":
			writeJSONResp(t, w, map[string]interface{}{
				"login":   "testuser",
				"user_id": float64(42),
			})
		case r.Method == "POST":
			createdBody = decodeReqBody(t, r)
			writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
		default:
			t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
		}
	}))
	defer server.Close()

	err := runBatchCreateShortcut(t, server, map[string]string{
		"names":       "desc-repo",
		"description": "shared description",
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if createdBody["description"] != "shared description" {
		t.Fatalf("description: got %q, want %q", createdBody["description"], "shared description")
	}
}

func TestBatchCreate_FromCSV(t *testing.T) {
	csvPath := writeTempCSV(t, "name,description,private\ncsv-repo1,desc one,false\ncsv-repo2,desc two,true\n")

	var createdBodies []map[string]interface{}
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.Method == "GET" && r.URL.Path == "/users/me.json":
			writeJSONResp(t, w, map[string]interface{}{
				"login":   "testuser",
				"user_id": float64(42),
			})
		case r.Method == "POST":
			createdBodies = append(createdBodies, decodeReqBody(t, r))
			writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
		default:
			t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
		}
	}))
	defer server.Close()

	err := runBatchCreateShortcut(t, server, map[string]string{"from": csvPath})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(createdBodies) != 2 {
		t.Fatalf("expected 2 creates, got %d", len(createdBodies))
	}
	if createdBodies[0]["name"] != "csv-repo1" {
		t.Fatalf("first name: got %q", createdBodies[0]["name"])
	}
	if createdBodies[0]["description"] != "desc one" {
		t.Fatalf("first description: got %q", createdBodies[0]["description"])
	}
	if createdBodies[1]["name"] != "csv-repo2" {
		t.Fatalf("second name: got %q", createdBodies[1]["name"])
	}
	if createdBodies[1]["private"] != true {
		t.Fatalf("second private: got %v, want true", createdBodies[1]["private"])
	}
}

func TestBatchCreate_PartialFailure(t *testing.T) {
	callCount := 0
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.Method == "GET" && r.URL.Path == "/users/me.json":
			writeJSONResp(t, w, map[string]interface{}{
				"login":   "testuser",
				"user_id": float64(42),
			})
		case r.Method == "POST":
			callCount++
			if callCount == 2 {
				w.WriteHeader(http.StatusUnprocessableEntity)
				return
			}
			writeJSONResp(t, w, map[string]interface{}{"id": float64(callCount)})
		default:
			t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
		}
	}))
	defer server.Close()

	err := runBatchCreateShortcut(t, server, map[string]string{
		"names": "ok1,fail1,ok2",
	})
	if err == nil {
		t.Fatal("expected error from partial failure, got nil")
	}
	if !strings.Contains(err.Error(), "failed to create") {
		t.Fatalf("error should mention failed count, got: %v", err)
	}
}

func TestBatchCreate_UserLookupFails(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusInternalServerError)
	}))
	defer server.Close()

	err := runBatchCreateShortcut(t, server, map[string]string{
		"names": "repo1",
	})
	if err == nil {
		t.Fatal("expected error, got nil")
	}
	if !strings.Contains(err.Error(), "failed to get current user") {
		t.Fatalf("error should mention user lookup, got: %v", err)
	}
}

func TestBatchCreate_UserMissingLogin(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		writeJSONResp(t, w, map[string]interface{}{
			"user_id": float64(42),
		})
	}))
	defer server.Close()

	err := runBatchCreateShortcut(t, server, map[string]string{
		"names": "repo1",
	})
	if err == nil {
		t.Fatal("expected error, got nil")
	}
	if !strings.Contains(err.Error(), "cannot determine current user login") {
		t.Fatalf("error should mention missing login, got: %v", err)
	}
}

func TestBatchCreate_CSVAndNamesCombined(t *testing.T) {
	csvPath := writeTempCSV(t, "name\ndual-repo\n")

	var createdNames []string
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.Method == "GET" && r.URL.Path == "/users/me.json":
			writeJSONResp(t, w, map[string]interface{}{
				"login":   "testuser",
				"user_id": float64(42),
			})
		case r.Method == "POST":
			body := decodeReqBody(t, r)
			createdNames = append(createdNames, body["name"].(string))
			writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
		default:
			t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
		}
	}))
	defer server.Close()

	err := runBatchCreateShortcut(t, server, map[string]string{
		"names": "inline-repo",
		"from":  csvPath,
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(createdNames) != 2 {
		t.Fatalf("expected 2 creates, got %d", len(createdNames))
	}
	if createdNames[0] != "inline-repo" {
		t.Fatalf("first: got %q", createdNames[0])
	}
	if createdNames[1] != "dual-repo" {
		t.Fatalf("second: got %q", createdNames[1])
	}
}

// ---- readRepoInputsFromCSV tests ----

func TestReadRepoInputsFromCSV_Normal(t *testing.T) {
	path := writeTempCSV(t, "name,description,private\nrepo1,desc1,true\nrepo2,desc2,false\nrepo3,,0\n")

	inputs, err := readRepoInputsFromCSV(path)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(inputs) != 3 {
		t.Fatalf("got %d inputs, want 3", len(inputs))
	}
	if inputs[0].Name != "repo1" || inputs[0].Description != "desc1" || !inputs[0].Private {
		t.Fatalf("input[0]: %+v", inputs[0])
	}
	if inputs[1].Name != "repo2" || inputs[1].Private {
		t.Fatalf("input[1]: %+v", inputs[1])
	}
	if inputs[2].Name != "repo3" || inputs[2].Private {
		t.Fatalf("input[2]: %+v", inputs[2])
	}
}

func TestReadRepoInputsFromCSV_MissingNameColumn(t *testing.T) {
	path := writeTempCSV(t, "title,description\nval1,desc1\n")
	_, err := readRepoInputsFromCSV(path)
	if err == nil {
		t.Fatal("expected error, got nil")
	}
}

func TestReadRepoInputsFromCSV_OnlyHeader(t *testing.T) {
	path := writeTempCSV(t, "name,description\n")
	_, err := readRepoInputsFromCSV(path)
	if err == nil {
		t.Fatal("expected error, got nil")
	}
}

func TestReadRepoInputsFromCSV_SkipsEmptyName(t *testing.T) {
	path := writeTempCSV(t, "name,description\nrepo1,desc1\n,desc2\nrepo2,desc3\n")

	inputs, err := readRepoInputsFromCSV(path)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(inputs) != 2 {
		t.Fatalf("got %d inputs, want 2", len(inputs))
	}
}

func TestReadRepoInputsFromCSV_PrivateParsing(t *testing.T) {
	path := writeTempCSV(t, "name,private\nr1,true\nr2,false\nr3,1\nr4,0\nr5,\n")

	inputs, err := readRepoInputsFromCSV(path)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(inputs) != 5 {
		t.Fatalf("got %d inputs, want 5", len(inputs))
	}
	if !inputs[0].Private {
		t.Fatal("r1 (true) should be private")
	}
	if inputs[1].Private {
		t.Fatal("r2 (false) should not be private")
	}
	if !inputs[2].Private {
		t.Fatal("r3 (1) should be private")
	}
	if inputs[3].Private {
		t.Fatal("r4 (0) should not be private")
	}
	if inputs[4].Private {
		t.Fatal("r5 (empty) should not be private")
	}
}

func TestReadRepoInputsFromCSV_FileNotFound(t *testing.T) {
	_, err := readRepoInputsFromCSV("/nonexistent/path.csv")
	if err == nil {
		t.Fatal("expected error, got nil")
	}
}

func TestReadRepoInputsFromCSV_CaseInsensitiveHeader(t *testing.T) {
	path := writeTempCSV(t, "NAME,Description,Private\nrepo1,desc1,TRUE\n")

	inputs, err := readRepoInputsFromCSV(path)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(inputs) != 1 {
		t.Fatalf("got %d inputs, want 1", len(inputs))
	}
	if inputs[0].Name != "repo1" {
		t.Fatalf("name: got %q", inputs[0].Name)
	}
	if !inputs[0].Private {
		t.Fatal("should be private")
	}
}

// ---- getCol tests ----

func TestGetCol_Found(t *testing.T) {
	col := map[string]int{"name": 0, "description": 1}
	record := []string{"my-repo", "my desc"}
	if got := getCol(record, col, "name"); got != "my-repo" {
		t.Fatalf("got %q", got)
	}
	if got := getCol(record, col, "description"); got != "my desc" {
		t.Fatalf("got %q", got)
	}
}

func TestGetCol_Missing(t *testing.T) {
	col := map[string]int{"name": 0}
	record := []string{"my-repo"}
	if got := getCol(record, col, "missing"); got != "" {
		t.Fatalf("got %q, want empty", got)
	}
}

func TestGetCol_IndexOutOfRange(t *testing.T) {
	col := map[string]int{"name": 5}
	record := []string{"my-repo"}
	if got := getCol(record, col, "name"); got != "" {
		t.Fatalf("got %q, want empty", got)
	}
}

// ---- runBatchUpdate tests ----

func TestBatchUpdate_DryRun(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		t.Fatalf("no API calls expected in dry-run mode, got %s %s", r.Method, r.URL.Path)
	}))
	defer server.Close()

	err := runBatchUpdateShortcut(t, server, map[string]string{
		"names":   "repo1,repo2",
		"dry-run": "true",
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}

func TestBatchUpdate_FromNames(t *testing.T) {
	var fetchedRepos []string
	var patchedBodies []map[string]interface{}
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.Method == "GET":
			name := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/owner/"), ".json")
			fetchedRepos = append(fetchedRepos, name)
			writeJSONResp(t, w, map[string]interface{}{
				"name":       name,
				"identifier": "ident-" + name,
			})
		case r.Method == "PATCH":
			patchedBodies = append(patchedBodies, decodeReqBody(t, r))
			writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
		default:
			t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
		}
	}))
	defer server.Close()

	err := runBatchUpdateShortcut(t, server, map[string]string{
		"names":   "repo-a,repo-b",
		"private": "true",
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(fetchedRepos) != 2 {
		t.Fatalf("expected 2 fetches, got %d", len(fetchedRepos))
	}
	if len(patchedBodies) != 2 {
		t.Fatalf("expected 2 patches, got %d", len(patchedBodies))
	}
	for _, body := range patchedBodies {
		if body["private"] != true {
			t.Fatalf("private should be true: %+v", body)
		}
	}
}

func TestBatchUpdate_NoNames(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
	}))
	defer server.Close()

	err := runBatchUpdateShortcut(t, server, map[string]string{})
	if err == nil {
		t.Fatal("expected error, got nil")
	}
}

func TestBatchUpdate_PrivatePublicConflict(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
	}))
	defer server.Close()

	err := runBatchUpdateShortcut(t, server, map[string]string{
		"names":   "repo1",
		"private": "true",
		"public":  "true",
	})
	if err == nil {
		t.Fatal("expected error, got nil")
	}
	if !strings.Contains(err.Error(), "cannot use both --private and --public") {
		t.Fatalf("error should mention conflict, got: %v", err)
	}
}

func TestBatchUpdate_SetPublic(t *testing.T) {
	var patchedBody map[string]interface{}
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.Method == "GET":
			writeJSONResp(t, w, map[string]interface{}{
				"name":       "repo1",
				"identifier": "abc123",
			})
		case r.Method == "PATCH":
			patchedBody = decodeReqBody(t, r)
			writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
		default:
			t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
		}
	}))
	defer server.Close()

	err := runBatchUpdateShortcut(t, server, map[string]string{
		"names":  "repo1",
		"public": "true",
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if patchedBody["private"] != false {
		t.Fatalf("public should set private=false, got %v", patchedBody["private"])
	}
}

func TestBatchUpdate_WithDescription(t *testing.T) {
	var patchedBody map[string]interface{}
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.Method == "GET":
			writeJSONResp(t, w, map[string]interface{}{
				"name":       "repo1",
				"identifier": "abc123",
			})
		case r.Method == "PATCH":
			patchedBody = decodeReqBody(t, r)
			writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
		default:
			t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
		}
	}))
	defer server.Close()

	err := runBatchUpdateShortcut(t, server, map[string]string{
		"names":       "repo1",
		"description": "updated description",
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if patchedBody["description"] != "updated description" {
		t.Fatalf("description: got %q", patchedBody["description"])
	}
}

func TestBatchUpdate_FromCSV(t *testing.T) {
	csvPath := writeTempCSV(t, "name\ncsv-repo1\ncsv-repo2\n")

	var fetchedRepos []string
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.Method == "GET":
			name := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/owner/"), ".json")
			fetchedRepos = append(fetchedRepos, name)
			writeJSONResp(t, w, map[string]interface{}{
				"name":       name,
				"identifier": "ident-" + name,
			})
		case r.Method == "PATCH":
			writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
		default:
			t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
		}
	}))
	defer server.Close()

	err := runBatchUpdateShortcut(t, server, map[string]string{"from": csvPath})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(fetchedRepos) != 2 {
		t.Fatalf("expected 2 fetches, got %d", len(fetchedRepos))
	}
}

func TestBatchUpdate_PartialFailure(t *testing.T) {
	callCount := 0
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		callCount++
		switch {
		case r.Method == "GET" && strings.Contains(r.URL.Path, "fail-repo"):
			w.WriteHeader(http.StatusNotFound)
		case r.Method == "GET":
			writeJSONResp(t, w, map[string]interface{}{
				"name":       "ok-repo",
				"identifier": "abc123",
			})
		case r.Method == "PATCH":
			writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
		default:
			t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
		}
	}))
	defer server.Close()

	err := runBatchUpdateShortcut(t, server, map[string]string{
		"names": "ok-repo,fail-repo",
	})
	if err == nil {
		t.Fatal("expected error from partial failure, got nil")
	}
	if !strings.Contains(err.Error(), "failed to update") {
		t.Fatalf("error should mention failed count, got: %v", err)
	}
}

func TestBatchUpdate_PreservesIdentifier(t *testing.T) {
	var patchedBody map[string]interface{}
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.Method == "GET":
			writeJSONResp(t, w, map[string]interface{}{
				"name":       "my-repo",
				"identifier": "xyz-789",
				"description": "old desc",
			})
		case r.Method == "PATCH":
			patchedBody = decodeReqBody(t, r)
			writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
		default:
			t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
		}
	}))
	defer server.Close()

	err := runBatchUpdateShortcut(t, server, map[string]string{
		"names":       "my-repo",
		"description": "new desc",
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if patchedBody["name"] != "my-repo" {
		t.Fatalf("name: got %q", patchedBody["name"])
	}
	if patchedBody["identifier"] != "xyz-789" {
		t.Fatalf("identifier: got %q", patchedBody["identifier"])
	}
	if patchedBody["description"] != "new desc" {
		t.Fatalf("description: got %q", patchedBody["description"])
	}
}

// ---- readNamesFromCSV tests ----

func TestReadNamesFromCSV_Normal(t *testing.T) {
	path := writeTempCSV(t, "name\nrepo1\nrepo2\nrepo3\n")

	names, err := readNamesFromCSV(path)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(names) != 3 {
		t.Fatalf("got %d names, want 3", len(names))
	}
	if names[0] != "repo1" || names[1] != "repo2" || names[2] != "repo3" {
		t.Fatalf("got %v", names)
	}
}

func TestReadNamesFromCSV_MissingNameColumn(t *testing.T) {
	path := writeTempCSV(t, "title,description\nval1,desc1\nval2,desc2\n")

	names, err := readNamesFromCSV(path)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(names) != 2 {
		t.Fatalf("got %d names, want 2 (falls back to col 0)", len(names))
	}
	if names[0] != "val1" || names[1] != "val2" {
		t.Fatalf("got %v", names)
	}
}

func TestReadNamesFromCSV_OnlyHeader(t *testing.T) {
	path := writeTempCSV(t, "name\n")
	_, err := readNamesFromCSV(path)
	if err == nil {
		t.Fatal("expected error, got nil")
	}
}

func TestReadNamesFromCSV_SkipsEmptyName(t *testing.T) {
	path := writeTempCSV(t, "name\nrepo1\n\nrepo2\n")

	names, err := readNamesFromCSV(path)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(names) != 2 {
		t.Fatalf("got %d names, want 2", len(names))
	}
}

func TestReadNamesFromCSV_FileNotFound(t *testing.T) {
	_, err := readNamesFromCSV("/nonexistent/path.csv")
	if err == nil {
		t.Fatal("expected error, got nil")
	}
}

func TestReadNamesFromCSV_CaseInsensitiveHeader(t *testing.T) {
	path := writeTempCSV(t, "NAME\nrepo1\nrepo2\n")

	names, err := readNamesFromCSV(path)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(names) != 2 {
		t.Fatalf("got %d names, want 2", len(names))
	}
}

func TestReadNamesFromCSV_ExtraColumns(t *testing.T) {
	path := writeTempCSV(t, "name,extra,another\nrepo1,x,y\nrepo2,a,b\n")

	names, err := readNamesFromCSV(path)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(names) != 2 {
		t.Fatalf("got %d names, want 2", len(names))
	}
	if names[0] != "repo1" || names[1] != "repo2" {
		t.Fatalf("got %v", names)
	}
}
