package mongo_test

import (
	"context"
	"testing"

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

func TestStoreSaveAndLoadChunkedSnapshotGraph(t *testing.T) {
	store, cleanup := setupMongoStore(t)
	defer cleanup()

	nodes := []graph.Node{
		{ID: "repo_test", Kind: graph.NodeKindRepository, Name: "ad/example"},
	}
	edges := make([]graph.Edge, 0, 300)
	for i := 0; i < 300; i++ {
		edges = append(edges, graph.Edge{
			ID:       "edge:snap#calls@" + itoa(i),
			Kind:     graph.EdgeKindCalls,
			SourceID: "sym:a",
			TargetID: "sym:b",
		})
	}

	artifact := graph.Artifact{
		SchemaVersion: graph.SchemaVersionV1,
		RepoID:        "ad/example",
		SnapshotID:    "snap_graph_chunked",
		CommitSHA:     "abc123",
		Nodes:         nodes,
		Edges:         edges,
	}

	artifactID, _, err := store.SaveSnapshotGraph(context.Background(), artifact, "")
	if err != nil {
		t.Fatalf("SaveSnapshotGraph: %v", err)
	}

	loaded, loadedID, ok, err := store.GetSnapshotGraphBySnapshot(context.Background(), "ad/example", "snap_graph_chunked")
	if err != nil {
		t.Fatalf("GetSnapshotGraphBySnapshot: %v", err)
	}
	if !ok {
		t.Fatal("expected snapshot graph to exist")
	}
	if loadedID != artifactID {
		t.Fatalf("artifact id: got %q want %q", loadedID, artifactID)
	}
	if len(loaded.Edges) != len(edges) {
		t.Fatalf("edges: got %d want %d", len(loaded.Edges), len(edges))
	}
}

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:])
}
