package system

import (
	"encoding/json"
	"kra/internal/biz/system"
	"testing"

	"kra/internal/service/dto"
)

func TestMenuDomainPreservesRelationIdentity(t *testing.T) {
	menu := menuDomain(&dto.MenuRequest{
		ID: 10,
		MenuButtons: []dto.MenuButtonRequest{{
			ID: 31, Name: "edit", Description: "编辑",
		}},
		Parameters: []dto.MenuParameterRequest{{
			ID: 21, Type: "query", Key: "id", Value: "1",
		}},
	})
	if !menu.CreatedAt.IsZero() || !menu.UpdatedAt.IsZero() {
		t.Fatalf("menu timestamps = (%v, %v), want zero before persistence", menu.CreatedAt, menu.UpdatedAt)
	}
	if len(menu.Buttons) != 1 || menu.Buttons[0].ID != 31 || menu.Buttons[0].MenuID != 10 || !menu.Buttons[0].CreatedAt.IsZero() || !menu.Buttons[0].UpdatedAt.IsZero() {
		t.Fatalf("button conversion = %+v", menu.Buttons)
	}
	if len(menu.Parameters) != 1 || menu.Parameters[0].ID != 21 || menu.Parameters[0].MenuID != 10 || !menu.Parameters[0].CreatedAt.IsZero() || !menu.Parameters[0].UpdatedAt.IsZero() {
		t.Fatalf("parameter conversion = %+v", menu.Parameters)
	}
}

func TestMenuResponseEmptyCollectionContracts(t *testing.T) {
	if got := menuResponses(nil); got != nil {
		t.Fatalf("base menu top-level nil = %#v, want nil", got)
	}
	if got := dynamicMenuResponses(nil); got == nil || len(got) != 0 {
		t.Fatalf("dynamic menu top-level empty = %#v, want non-nil empty slice", got)
	}

	base := menuResponse(&system.Menu{Children: nil, Buttons: []*system.MenuButton{}, Parameters: []*system.MenuParameter{}})
	if base.Children != nil {
		t.Fatalf("leaf children = %#v, want nil", base.Children)
	}
	if base.MenuButtons == nil || base.Parameters == nil {
		t.Fatalf("preloaded empty relations = (%#v, %#v), want empty slices", base.MenuButtons, base.Parameters)
	}
	encoded, err := json.Marshal(base)
	if err != nil {
		t.Fatal(err)
	}
	var payload map[string]any
	if err := json.Unmarshal(encoded, &payload); err != nil {
		t.Fatal(err)
	}
	if value, ok := payload["authoritys"]; !ok || value != nil {
		t.Fatalf("authoritys JSON = %#v (present=%v), want explicit null", value, ok)
	}
}
