package installer

import (
	"net"
	"strings"
	"testing"
)

func TestParseNginxProxyConfig(t *testing.T) {
	cfg, err := ParseNginxProxyConfig(strings.NewReader(`
apiVersion: v1
kind: ConfigMap
metadata:
  name: proxy-backend-config
  namespace: foo
data:
nginx.conf: |
# user       www www;
worker_processes  1;
error_log   /dev/null   crit;
# pid        logs/nginx.pid;
worker_rlimit_nofile 8192;
events {
	worker_connections  1024;
}
http {
	error_log /var/log/nginx/error.log debug;
	log_format dodo '$http_host $proxy_host $status';
	access_log /var/log/nginx/access.log dodo;
	map $http_host $backend {
		a A;
		b B;
	}
	server {
		listen 9090;
		location / {
			resolver 1.1.1.1;
			resolver 2.2.2.2;
			proxy_pass http://$backend;
		}
	}
}
stream {
	server {
		listen 9091;
		proxy_pass foo:1;
	}
	server {
		listen 9092 udp;
		proxy_pass bar:2;
	}
	server {
		listen 9093;
		proxy_pass dev:3;
	}
}
`))
	if err != nil {
		t.Fatal(err)
	}
	if cfg.Namespace != "foo" {
		t.Errorf("invalid namespace: expeced foo, got %s", cfg.Namespace)
	}
	if cfg.IngressPort != 9090 {
		t.Errorf("invalid port: expected 9090, got %d", cfg.IngressPort)
	}
	if len(cfg.Resolvers) != 2 ||
		!cfg.Resolvers[0].Equal(net.ParseIP("1.1.1.1")) ||
		!cfg.Resolvers[1].Equal(net.ParseIP("2.2.2.2")) {
		t.Errorf("invalid resolvers: expected [1.1.1.1 2.2.2.2], got %s", cfg.Resolvers)
	}
	if len(cfg.Ingress) != 2 ||
		cfg.Ingress["a"] != "A" ||
		cfg.Ingress["b"] != "B" {
		t.Errorf("invalid ingress proxies: expected map[a:A, b:B], got %s", cfg.Ingress)
	}
	if len(cfg.TCP) != 2 ||
		cfg.TCP[9091] != "foo:1" ||
		cfg.TCP[9093] != "dev:3" {
		t.Errorf("invalid TCP proxies: expected map[9091:foo:1, 9093:dev:3], got %v", cfg.TCP)
	}
	if len(cfg.UDP) != 1 ||
		cfg.UDP[9092] != "bar:2" {
		t.Errorf("invalid UDP proxies: expected map[9092:bar:2], got %v", cfg.UDP)
	}
}

func TestRenderNginxProxyConfig(t *testing.T) {
	cfg := NginxProxyConfig{
		IngressPort: 8080,
		Resolvers:   []net.IP{net.ParseIP("1.1.1.1"), net.ParseIP("2.2.2.2")},
		Ingress: map[string]string{
			"a": "A",
			"b": "B",
		},
		TCP: map[int]string{
			1: "foo:1",
			3: "dev:3",
		},
		UDP: map[int]string{
			2: "bar:2",
		},
		PreConf: []string{"line1", "line2"},
	}
	var buf strings.Builder
	if err := cfg.Render(&buf); err != nil {
		t.Fatal(err)
	}
	t.Log(buf.String())
}
