package server

import (
	"local/rssmon3/config"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"testing"
)

var validNS = "ns"
var validKey = "key"
var validValue = "value"

func TestRoutes(t *testing.T) {
	os.Setenv("DB", "MAP")
	os.Args = []string{"nothing"}
	if err := config.New(); err != nil {
		t.Fatal(err)
	}
	s := New(nil)
	if err := s.Routes(); err != nil {
		t.Fatalf("cannot routes(): %v", err)
	}
	cases := []struct {
		path   string
		method string
		status int
	}{
		{
			path:   "/api/tag",
			method: "GET",
			status: http.StatusNotFound,
		},
		{
			path:   "/api/tag/",
			method: "GET",
			status: http.StatusNotFound,
		},
		{
			path:   "/api/tag/key",
			method: "GET",
			status: http.StatusOK,
		},
		{
			path:   "/api/tag/key",
			method: "POST",
			status: http.StatusNotFound,
		},
	}

	for i, c := range cases {
		r, err := http.NewRequest(c.method, c.path, strings.NewReader(validValue))
		if err != nil {
			t.Fatalf("err making request: %v", err)
		}
		w := httptest.NewRecorder()
		s.ServeHTTP(w, r)
		if w.Code != c.status {
			t.Errorf("[%d] wrong status for %q on %q: %v, want %v", i, c.method, c.path, w.Code, c.status)
		}
	}
}

func TestServerHandlersNotFound(t *testing.T) {
	os.Args = []string{"a"}
	config.New()
	s := New(nil)
	w := httptest.NewRecorder()
	r, _ := http.NewRequest("GET", "/", nil)
	s.notFound(w, r)
	if w.Code != http.StatusNotFound {
		t.Error(w.Code)
	}
}

func TestServerHandlers(t *testing.T) {
	os.Args = []string{"a"}
	config.New()
	s := New(nil)
	cases := []struct {
		foo  func(http.ResponseWriter, *http.Request, error)
		code int
	}{
		{
			foo:  s.userError,
			code: http.StatusBadRequest,
		},
		{
			foo:  s.error,
			code: http.StatusInternalServerError,
		},
	}

	for _, c := range cases {
		w := httptest.NewRecorder()
		r, _ := http.NewRequest("GET", "/", nil)
		c.foo(w, r, nil)
		if w.Code != c.code {
			t.Errorf("unexpected status: want %v, got %v", c.code, w.Code)
		}
	}
}
