package output

import (
	"bytes"
	"strings"
	"testing"
)

func TestPrintTable_WrappedEmptyList(t *testing.T) {
	env := &Envelope{OK: true, Data: map[string]interface{}{
		"count":    0,
		"projects": []interface{}{},
	}}
	var buf bytes.Buffer
	if err := PrintTo(&buf, env, "table"); err != nil {
		t.Fatalf("PrintTo failed: %v", err)
	}
	got := buf.String()
	if !strings.Contains(got, "No results") {
		t.Errorf("expected 'No results', got: %q", got)
	}
}

func TestPrintTable_WrappedList(t *testing.T) {
	env := &Envelope{OK: true, Data: map[string]interface{}{
		"count": 2,
		"projects": []interface{}{
			map[string]interface{}{"id": 1.0, "name": "alpha"},
			map[string]interface{}{"id": 2.0, "name": "beta"},
		},
	}}
	var buf bytes.Buffer
	if err := PrintTo(&buf, env, "table"); err != nil {
		t.Fatalf("PrintTo failed: %v", err)
	}
	got := buf.String()
	if !strings.Contains(got, "alpha") || !strings.Contains(got, "beta") {
		t.Errorf("expected alpha/beta in output, got: %q", got)
	}
	if !strings.Contains(got, "id") || !strings.Contains(got, "name") {
		t.Errorf("expected header id/name, got: %q", got)
	}
}

func TestUnwrapSingleListField_KnownName(t *testing.T) {
	m := map[string]interface{}{
		"count":    2.0,
		"projects": []interface{}{map[string]interface{}{"id": 1.0}},
	}
	got := unwrapSingleListField(m)
	if got == nil || len(got) != 1 {
		t.Fatalf("expected slice len=1, got %v", got)
	}
}

func TestUnwrapSingleListField_MultipleUnknownListsReturnsNil(t *testing.T) {
	// 两个未知名字的 list 字段 — 无法自动选择，返回 nil
	m := map[string]interface{}{
		"foo_list": []interface{}{map[string]interface{}{"id": 1.0}},
		"bar_list": []interface{}{map[string]interface{}{"id": 2.0}},
	}
	if got := unwrapSingleListField(m); got != nil {
		t.Errorf("expected nil for multiple unknown list fields, got len=%d", len(got))
	}
}

func TestUnwrapSingleListField_KnownNamePreferred(t *testing.T) {
	// 已知 name 优先 — 即使有其他 list 字段也用 known name
	m := map[string]interface{}{
		"projects": []interface{}{map[string]interface{}{"id": 1.0}},
		"users":    []interface{}{map[string]interface{}{"id": 2.0}},
	}
	got := unwrapSingleListField(m)
	if got == nil || len(got) != 1 {
		t.Fatalf("expected projects slice len=1, got %v", got)
	}
	first := got[0].(map[string]interface{})
	if first["id"] != 1.0 {
		t.Errorf("expected projects[0].id=1, got %v", first["id"])
	}
}
