package xray

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

	"github.com/stretchr/testify/assert"
)

var rt *roundtripper

func init() {
	rt = &roundtripper{
		Base: http.DefaultTransport,
	}
}

func TestRoundTrip(t *testing.T) {
	var responseContentLength int
	var headers xRayHeaders
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		headers = parseHeadersForTest(r.Header)

		b := []byte(`200 - Nothing to see`)
		responseContentLength = len(b)
		w.WriteHeader(http.StatusOK)
		w.Write(b)
	}))

	defer ts.Close()

	reader := strings.NewReader("")
	req := httptest.NewRequest("GET", ts.URL, reader)

	_, err := rt.RoundTrip(req)
	assert.NoError(t, err)

	s, e := testDaemon.Recv()
	assert.NoError(t, e)

	assert.Equal(t, "remote", s.Namespace)
	assert.Equal(t, "GET", s.HTTP.Request.Method)
	assert.Equal(t, ts.URL, s.HTTP.Request.URL)
	assert.Equal(t, 200, s.HTTP.Response.Status)
	assert.Equal(t, responseContentLength, s.HTTP.Response.ContentLength)
	assert.Equal(t, headers.RootTraceID, s.TraceID)
	assert.Equal(t, headers.ParentID, s.ID)
	//not checking for sampling here
}

func TestBadRoundTrip(t *testing.T) {
	reader := strings.NewReader("")
	req := httptest.NewRequest("GET", "httpz://localhost:8000", reader)

	_, err := rt.RoundTrip(req)
	assert.Error(t, err)

	s, e := testDaemon.Recv()
	assert.NoError(t, e)

	assert.Equal(t, fmt.Sprintf("%v", err), s.Cause.Exceptions[0].Message)
}
