package example

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestAuthLayer(t *testing.T) {
	// the layerd design allows for easy replacement of lower layers
	layer := AuthLayer(alwaysOK())
	cases := map[string]int{
		"GET /fruits": 200,
		"GET /keys":   401,
	}
	checkResp(t, layer, cases)
}

func TestEndpoints(t *testing.T) {
	layer := Endpoints()
	cases := map[string]int{
		"GET /fruits": 200,
		"GET /keys":   200,
		"POST /keys":  405,
	}
	checkResp(t, layer, cases)
}

func checkResp(t *testing.T, h http.Handler, cases map[string]int) {
	for pattern, exp := range cases {
		t.Run(pattern, func(t *testing.T) {
			// require
			method, path := parsePattern(pattern)
			r := httptest.NewRequest(method, path, http.NoBody)
			// do
			resp := recordResp(h, r)
			// ensure
			ensure(t,
				statusCodeIs(resp.StatusCode, exp),
			)
		})
	}
}

// parsePattern returns method and path
func parsePattern(pattern string) (string, string) {
	parts := strings.Split(pattern, " ")
	return parts[0], parts[1]
}

func alwaysOK() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
	}
}
