package proxyio

import (
	"strings"
	"testing"

	"github.com/prism/proxy/internal/store"
)

func TestExportLinksSocks5(t *testing.T) {
	text := ExportLinks([]store.ProxyNode{{
		Name:      "HK-1",
		Type:      "socks5",
		RawConfig: `{"type":"socks5","server":"1.2.3.4","port":1080,"username":"u","password":"p"}`,
		Enabled:   true,
	}})
	if !strings.Contains(text, "socks5://u:p@1.2.3.4:1080#HK-1") {
		t.Fatalf("got %q", text)
	}
}

func TestParseJSONDoc(t *testing.T) {
	nodes, err := ParseJSON([]byte(`{"version":1,"nodes":[{"name":"n1","type":"socks5","raw_config":{"server":"1.1.1.1","port":1080}}]}`))
	if err != nil || len(nodes) != 1 {
		t.Fatalf("nodes=%+v err=%v", nodes, err)
	}
	stored, errs := ToStoreNodes(nodes)
	if len(errs) != 0 || len(stored) != 1 || stored[0].Name != "n1" {
		t.Fatalf("stored=%+v errs=%v", stored, errs)
	}
}

func TestAssignUniqueNames(t *testing.T) {
	nodes := []store.ProxyNode{{Name: "a"}, {Name: "a"}}
	reserved := map[string]bool{"a": true}
	AssignUniqueNames(nodes, reserved)
	if nodes[0].Name != "a_2" || nodes[1].Name != "a_3" {
		t.Fatalf("names: %s, %s", nodes[0].Name, nodes[1].Name)
	}
}
