package proxy_test

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

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/tidbcloud/cluster-service-ng/domain/app/proxy"
)

type mockAdapter struct {
	backendURL string
}

func (m *mockAdapter) GetKongAddressByClusterId(ctx context.Context, clusterID string) (string, string, error) {
	return m.backendURL[len("http://"):], "", nil
}

func (m *mockAdapter) GetKongAddressBySharedPoolId(ctx context.Context, sharedPoolID string) (string, string, error) {
	return m.backendURL[len("http://"):], "", nil
}

func TestSetUpReverseProxy(t *testing.T) {
	backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		assert.Equal(t, "/dataflow-agent/tasks/list", r.URL.Path)
		_, _ = w.Write([]byte(`{"msg":"backend OK"}`))
	}))
	defer backendServer.Close()

	gin.SetMode(gin.TestMode)
	router := gin.New()
	mock := &mockAdapter{backendURL: backendServer.URL}

	proxy.SetUpReverseProxy(router, mock)

	proxyServer := httptest.NewServer(router)
	defer proxyServer.Close()

	req, _ := http.NewRequest(http.MethodGet, proxyServer.URL+"/proxy/clusters/test-cluster/dataflow-agent/tasks/list", http.NoBody)
	resp, err := http.DefaultClient.Do(req)
	require.NoError(t, err)
	defer func() { _ = resp.Body.Close() }()

	body, _ := io.ReadAll(resp.Body)
	assert.Equal(t, http.StatusOK, resp.StatusCode)
	assert.Contains(t, string(body), "backend OK")
}
