package compat

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

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestClustersPath_RewritesCorrectly(t *testing.T) {
	ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
	ctx.Request = &http.Request{
		URL:    &url.URL{Path: "/inner/mgmt/compat/v1/clusters/123"},
		Method: http.MethodGet,
	}
	newPath, err := rewriteOldCompatApiPath(ctx)
	require.NoError(t, err)
	assert.Equal(t, "/dataplane/clusters/123", newPath)
}

func TestNetworksPath_RewritesCorrectly(t *testing.T) {
	ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
	ctx.Request = &http.Request{
		URL:    &url.URL{Path: "/inner/mgmt/compat/v1/networks/456"},
		Method: http.MethodGet,
	}
	ctx.Request.URL.RawQuery = "providerName=aws&regionName=us-west-2"
	newPath, err := rewriteOldCompatApiPath(ctx)
	require.NoError(t, err)
	assert.Equal(t, "/dataplane/networks/456/aws/us-west-2", newPath)
}

func TestProvidersPath_RewritesCorrectly(t *testing.T) {
	ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
	ctx.Request = &http.Request{
		URL:    &url.URL{Path: "/inner/mgmt/compat/v1/providers/gcp"},
		Method: http.MethodGet,
	}
	newPath, err := rewriteOldCompatApiPath(ctx)
	require.NoError(t, err)
	assert.Equal(t, "/dataplane/providers/gcp", newPath)
}

func TestInvalidPath_DoesNotRewrite(t *testing.T) {
	ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
	ctx.Request = &http.Request{
		URL:    &url.URL{Path: "/inner/mgmt/compat/v1/invalid"},
		Method: http.MethodGet,
	}
	newPath, err := rewriteOldCompatApiPath(ctx)
	require.NoError(t, err)
	assert.Equal(t, "/inner/mgmt/compat/v1/invalid", newPath)
}
