package ai

import (
	"encoding/json"
	"testing"
)

func TestDispatchUnknownTool(t *testing.T) {
	router := NewToolRouter()

	_, err := router.Dispatch("nonexistent_tool", json.RawMessage(`{}`))
	if err == nil {
		t.Error("expected error for unknown tool")
	}
	if err.Error() != "unknown tool: nonexistent_tool" {
		t.Errorf("unexpected error message: %v", err)
	}
}

func TestDispatchListSessions(t *testing.T) {
	router := NewToolRouter()

	// With nil services, list_sessions should return empty result
	result, err := router.Dispatch("list_sessions", json.RawMessage(`{}`))
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	m, ok := result.(map[string]interface{})
	if !ok {
		t.Fatalf("expected map result, got %T", result)
	}

	ssh, ok := m["ssh"].([]interface{})
	if !ok {
		t.Fatal("expected ssh key in result")
	}
	if len(ssh) != 0 {
		t.Errorf("expected empty ssh list, got %d items", len(ssh))
	}

	rdp, ok := m["rdp"].([]interface{})
	if !ok {
		t.Fatal("expected rdp key in result")
	}
	if len(rdp) != 0 {
		t.Errorf("expected empty rdp list, got %d items", len(rdp))
	}
}

func TestDispatchTerminalWriteNoService(t *testing.T) {
	router := NewToolRouter()

	_, err := router.Dispatch("terminal_write", json.RawMessage(`{"sessionId":"abc","text":"ls\n"}`))
	if err == nil {
		t.Error("expected error when SSH service is nil")
	}
}

func TestDispatchTerminalReadNoService(t *testing.T) {
	router := NewToolRouter()

	_, err := router.Dispatch("terminal_read", json.RawMessage(`{"sessionId":"abc"}`))
	if err == nil {
		t.Error("expected error when AI service is nil")
	}
}

func TestDispatchSFTPListNoService(t *testing.T) {
	router := NewToolRouter()

	_, err := router.Dispatch("sftp_list", json.RawMessage(`{"sessionId":"abc","path":"/"}`))
	if err == nil {
		t.Error("expected error when SFTP service is nil")
	}
}

func TestDispatchDisconnectNoService(t *testing.T) {
	router := NewToolRouter()

	_, err := router.Dispatch("disconnect", json.RawMessage(`{"sessionId":"abc"}`))
	if err == nil {
		t.Error("expected error when no services available")
	}
}
