package node_test

import (
	"testing"

	"iop/apps/edge/internal/node"
	"iop/packages/go/config"
)

func TestBuildConfigPayloadProviderOnly(t *testing.T) {
	record := &node.NodeRecord{
		ID: "node", Alias: "node", Token: "token",
		Providers: []config.NodeProviderConf{
			{ID: "ollama-local", Type: "ollama", Category: config.CategoryLocalInference, BaseURL: "http://127.0.0.1:11434", Models: []string{"model"}, Capacity: 1},
			{ID: "api", Type: "openai_api", Category: config.CategoryAPI, Endpoint: "http://127.0.0.1:8000/v1", Models: []string{"model"}, Capacity: 2},
		},
	}
	payload, err := node.BuildConfigPayload(record)
	if err != nil {
		t.Fatal(err)
	}
	if len(payload.GetAdapters()) != 2 {
		t.Fatalf("adapters = %d", len(payload.GetAdapters()))
	}
	if payload.GetAdapters()[0].GetType() != "ollama" || payload.GetAdapters()[1].GetType() != "openai_compat" {
		t.Fatalf("adapters = %#v", payload.GetAdapters())
	}
}

func TestBuildConfigPayloadIncludesCompleteWorkspaceCatalog(t *testing.T) {
	record := &node.NodeRecord{Workspaces: []config.WorkspaceDefinition{{
		Ref:                  "mac-workspace",
		Platform:             "darwin",
		Root:                 "/operator/workspace",
		Operations:           []config.WorkspaceOperation{config.WorkspaceOpRead, config.WorkspaceOpCommand},
		Commands:             []config.WorkspaceCommandDefinition{{ID: "test", Executable: "/usr/bin/test", Args: []string{"-f", "README.md"}}},
		EnvironmentAllowlist: []string{"LANG"},
		MaxReadBytes:         1024,
		MaxWriteBytes:        2048,
		MaxOutputBytes:       4096,
		MaxCommandTimeoutMS:  5000,
	}}}
	payload, err := node.BuildConfigPayload(record)
	if err != nil {
		t.Fatal(err)
	}
	if len(payload.GetWorkspaces()) != 1 {
		t.Fatalf("workspaces = %d, want 1", len(payload.GetWorkspaces()))
	}
	workspace := payload.GetWorkspaces()[0]
	if workspace.GetRef() != "mac-workspace" || workspace.GetPlatform() != "darwin" || workspace.GetRoot() != "/operator/workspace" {
		t.Fatalf("workspace identity mismatch: %+v", workspace)
	}
	if len(workspace.GetOperations()) != 2 || len(workspace.GetCommands()) != 1 || workspace.GetCommands()[0].GetId() != "test" || workspace.GetCommands()[0].GetExecutable() != "/usr/bin/test" {
		t.Fatalf("workspace capabilities mismatch: %+v", workspace)
	}
	if workspace.GetEnvironmentAllowlist()[0] != "LANG" || workspace.GetMaxReadBytes() != 1024 || workspace.GetMaxWriteBytes() != 2048 || workspace.GetMaxOutputBytes() != 4096 || workspace.GetMaxCommandTimeoutMs() != 5000 {
		t.Fatalf("workspace bounds mismatch: %+v", workspace)
	}
}
