package gemini_test

import (
	"bytes"
	"testing"

	"tildegit.org/tjp/sliderule/gemini"
)

func TestParseRequest(t *testing.T) {
	table := []struct {
		input    string
		scheme   string
		host     string
		path     string
		query    string
		fragment string
		err      error
	}{
		{
			input:    "gemini://foo.com/bar?baz#qux\r\n",
			scheme:   "gemini",
			host:     "foo.com",
			path:     "/bar",
			query:    "baz",
			fragment: "qux",
			err:      nil,
		},
		{
			input:    "//foo.com/path\r\n",
			scheme:   "gemini",
			host:     "foo.com",
			path:     "/path",
			query:    "",
			fragment: "",
			err:      nil,
		},
		{
			input:    "/path\r\n",
			scheme:   "gemini",
			host:     "",
			path:     "/path",
			query:    "",
			fragment: "",
			err:      nil,
		},
		{
			input:    "gemini://invalid.com/line/ending",
			scheme:   "",
			host:     "",
			path:     "",
			query:    "",
			fragment: "",
			err:      gemini.InvalidRequestLineEnding,
		},
	}

	for _, test := range table {
		t.Run(test.input, func(t *testing.T) {
			req, err := gemini.ParseRequest(bytes.NewBufferString(test.input))
			if err != test.err {
				t.Fatalf("expected error %q, got %q", test.err, err)
			}

			if err != nil {
				return
			}

			if req.Scheme != test.scheme {
				t.Errorf("expected scheme %q, got %q", test.scheme, req.Scheme)
			}
			if req.Host != test.host {
				t.Errorf("expected host %q, got %q", test.host, req.Host)
			}
			if req.Path != test.path {
				t.Errorf("expected path %q, got %q", test.path, req.Path)
			}
			if req.RawQuery != test.query {
				t.Errorf("expected query %q, got %q", test.query, req.RawQuery)
			}
			if req.Fragment != test.fragment {
				t.Errorf("expected fragment %q, got %q", test.fragment, req.Fragment)
			}
		})
	}
}