package mongo

import (
	"testing"

	"bit.admedia.com/scm/ad/adpilot-indexing-code-parser.com/internal/contracts/graph"
)

func TestSplitGraphPayloadSinglePart(t *testing.T) {
	nodes := []graph.Node{
		{ID: "file:main.go", Kind: graph.NodeKindFile, Name: "main.go", Path: "main.go"},
		{ID: "sym:main.go#Main", Kind: graph.NodeKindSymbol, Name: "Main", Path: "main.go"},
	}
	edges := []graph.Edge{
		{ID: "e1", Kind: graph.EdgeKindDefines, SourceID: "file:main.go", TargetID: "sym:main.go#Main"},
	}

	parts := splitGraphPayload(nodes, edges, 1<<20)
	if len(parts) != 1 {
		t.Fatalf("expected 1 part, got %d", len(parts))
	}
	if len(parts[0].Nodes) != 2 || len(parts[0].Edges) != 1 {
		t.Fatalf("unexpected single part: %+v", parts[0])
	}
}

func TestSplitGraphPayloadMultipleParts(t *testing.T) {
	nodes := []graph.Node{
		{ID: "file:big.go", Kind: graph.NodeKindFile, Name: "big.go", Path: "big.go"},
	}
	edges := make([]graph.Edge, 0, 200)
	for i := 0; i < 200; i++ {
		edges = append(edges, graph.Edge{
			ID:       "edge:big.go#calls@" + itoa(i) + "#sym:big.go#fn#sym:pkg#Call",
			Kind:     graph.EdgeKindCalls,
			SourceID: "sym:big.go#fn",
			TargetID: "sym:pkg#Call",
		})
	}

	parts := splitGraphPayload(nodes, edges, 512)
	if len(parts) < 2 {
		t.Fatalf("expected multiple parts with 512 byte limit, got %d", len(parts))
	}
	if len(parts[0].Nodes) != 1 {
		t.Fatalf("part 0 should contain all nodes, got %d", len(parts[0].Nodes))
	}
	for i := 1; i < len(parts); i++ {
		if len(parts[i].Nodes) != 0 {
			t.Fatalf("part %d should not contain nodes", i)
		}
	}

	gotNodes, gotEdges := reassembleGraphPayload(parts)
	if len(gotNodes) != len(nodes) {
		t.Fatalf("reassembled nodes: got %d want %d", len(gotNodes), len(nodes))
	}
	if len(gotEdges) != len(edges) {
		t.Fatalf("reassembled edges: got %d want %d", len(gotEdges), len(edges))
	}
}

func TestEffectiveMaxPartBytes(t *testing.T) {
	if got := effectiveMaxPartBytes(0); got != defaultMaxPartBytes {
		t.Fatalf("default: got %d want %d", got, defaultMaxPartBytes)
	}
	if got := effectiveMaxPartBytes(1024); got != 1024 {
		t.Fatalf("custom: got %d", got)
	}
}

func itoa(n int) string {
	if n == 0 {
		return "0"
	}
	var buf [20]byte
	i := len(buf)
	for n > 0 {
		i--
		buf[i] = byte('0' + n%10)
		n /= 10
	}
	return string(buf[i:])
}
