package view

import (
	"local/dndex/config"
	"net/http"
	"net/url"
	"os"
	"testing"
)

func TestGetNamespace(t *testing.T) {
	os.Args = os.Args[:1]

	cases := map[string]struct {
		url     string
		want    string
		invalid bool
	}{
		"no query param, not files, should fail": {
			url:     "/",
			invalid: true,
		},
		"empty query param, not files, should fail": {
			url:     "/a?namespace=",
			invalid: true,
		},
		"query param, not files": {
			url:  "/a?namespace=OK",
			want: "OK",
		},
		"files, no query param": {
			url:  config.New().FilePrefix + "/OK",
			want: "OK",
		},
	}

	for name, d := range cases {
		c := d
		t.Run(name, func(t *testing.T) {
			c.url = "http://host.tld:80" + c.url
			uri, err := url.Parse(c.url)
			if err != nil {
				t.Fatal(err)
			}

			ns, err := getNamespace(&http.Request{URL: uri})
			if err != nil && !c.invalid {
				t.Fatal(c.invalid, err)
			} else if err == nil && ns != c.want {
				t.Fatal(c.want, ns)
			}

			authns, err := getAuthNamespace(&http.Request{URL: uri})
			if err != nil && !c.invalid {
				t.Fatal(c.invalid, err)
			} else if err == nil && authns != c.want+"."+AuthKey {
				t.Fatal(c.want+"."+AuthKey, authns)
			}
		})
	}
}
