package system

import (
	"context"
	"testing"
)

func TestDepartmentTreeAndSearchPreserveCollectionShapes(t *testing.T) {
	data := newTransactionTestData(t)
	ctx := context.Background()
	root := departmentPO{Name: "root", ParentID: 0, Ancestors: "0"}
	if err := data.gormDB.WithContext(ctx).Create(&root).Error; err != nil {
		t.Fatal(err)
	}
	child := departmentPO{Name: "child", ParentID: root.ID, Ancestors: "0"}
	if err := data.gormDB.WithContext(ctx).Create(&child).Error; err != nil {
		t.Fatal(err)
	}
	repo := &departmentRepo{data: data}

	tree, err := repo.ListDepartments(ctx, "")
	if err != nil {
		t.Fatal(err)
	}
	if len(tree) != 1 || len(tree[0].Children) != 1 || tree[0].Children[0].Children == nil {
		t.Fatalf("tree collection shape = %+v", tree)
	}

	search, err := repo.ListDepartments(ctx, "child")
	if err != nil {
		t.Fatal(err)
	}
	if len(search) != 1 || search[0].Children != nil {
		t.Fatalf("search collection shape = %+v", search)
	}
}

func TestPositionListKeepsZeroLimitBehavior(t *testing.T) {
	data := newTransactionTestData(t)
	ctx := context.Background()
	if err := data.gormDB.WithContext(ctx).Create(&positionPO{Name: "operator"}).Error; err != nil {
		t.Fatal(err)
	}
	items, total, err := (&positionRepo{data: data}).ListPositions(ctx, 0, 0, nil)
	if err != nil {
		t.Fatal(err)
	}
	if total != 1 || len(items) != 0 {
		t.Fatalf("zero-limit result: total=%d items=%+v", total, items)
	}
}
