package metrics

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestMiddleware(t *testing.T) {
	// Pick a port that's not commonly used. Ideally we should randomly pick an unused port.
	port := 35555
	metricsPort = &port
	StartMetricServer()

	handler := Middleware(http.NotFoundHandler())
	req := httptest.NewRequest("GET", "/", nil)
	recorder := httptest.NewRecorder()
	handler.ServeHTTP(recorder, req)

	if recorder.Code != http.StatusNotFound {
		t.Fatalf("cli.Get code got = %v, want = %v", recorder.Code, http.StatusNotFound)
	}

	mcli := &http.Client{}
	resp, err := mcli.Get(fmt.Sprintf("http://localhost:%d/metrics", port))
	if err != nil {
		t.Fatalf("mcli.Get err got = %v, want = %v", err, nil)
	}
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("mcli.Get code got = %v, want = %v", resp.StatusCode, http.StatusOK)
	}
	bodyBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("Unable to read the response body: %v", err)
	}
	if !strings.Contains(string(bodyBytes), "http_requests_total") {
		t.Fatalf("mcli.Get = \n%s should include http_requests_total", string(bodyBytes))
	}
	if !strings.Contains(string(bodyBytes), "http_response_time_seconds") {
		t.Fatalf("mcli.Get = \n%s should include http_response_time_seconds", string(bodyBytes))
	}
}
