package rest

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

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

func TestRouteProxyPreservesTargetBasePath(t *testing.T) {
	var gotPath string
	var gotQuery string
	upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		gotPath = r.URL.Path
		gotQuery = r.URL.RawQuery
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"ok":true}`))
	}))
	defer upstream.Close()

	t.Setenv("TOKEN_AGGREGATION_API_BASE", upstream.URL+"/token-aggregation")

	server := NewServer(nil, 138)
	req := httptest.NewRequest(http.MethodGet, "/api/v1/routes/tree?chainId=138&amountIn=1000000", nil)
	w := httptest.NewRecorder()

	server.handleRouteDecisionTree(w, req)

	require.Equal(t, http.StatusOK, w.Code)
	require.Equal(t, "/token-aggregation/api/v1/routes/tree", gotPath)
	require.Equal(t, "chainId=138&amountIn=1000000", gotQuery)
}

func TestRouteProxyHandlesBaseURLWithoutPath(t *testing.T) {
	var gotPath string
	upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		gotPath = r.URL.Path
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"ok":true}`))
	}))
	defer upstream.Close()

	t.Setenv("TOKEN_AGGREGATION_API_BASE", upstream.URL)

	server := NewServer(nil, 138)
	req := httptest.NewRequest(http.MethodGet, "/api/v1/routes/depth?chainId=138", nil)
	w := httptest.NewRecorder()

	server.handleRouteDepth(w, req)

	require.Equal(t, http.StatusOK, w.Code)
	require.Equal(t, "/api/v1/routes/depth", gotPath)
}
