package middlewares

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/AlchemyTelcoSolutions/xutils-go/xlogger"
	"github.com/go-chi/chi/v5"
	"github.com/stretchr/testify/assert"
)

func TestProxyNotFoundPaths(t *testing.T) {
	t.Parallel()

	testSuite := []struct {
		name           string
		testPath       string
		registeredPath string
		proxyNotFound  func() ProxyNotFoundPathInterface
		statusExpected int
	}{
		{
			name:           "allowed_all_endpoints",
			testPath:       "/allowed",
			registeredPath: "/allowed",
			proxyNotFound: func() ProxyNotFoundPathInterface {
				return &mockForward{}
			},
			statusExpected: http.StatusOK,
		},
		{
			name:           "allowed_redirect_endpoint",
			testPath:       "/original/path/with/more",
			registeredPath: "/original/path/with/more",
			proxyNotFound: func() ProxyNotFoundPathInterface {
				return &mockForward{}
			},
			statusExpected: http.StatusOK,
		},
		{
			name:           "not_allowed_endpoint_proxy",
			testPath:       "/not_allowed/path/with/more",
			registeredPath: "/allowed/path/with/more",
			proxyNotFound: func() ProxyNotFoundPathInterface {
				return &mockForward{}
			},
			statusExpected: http.StatusHTTPVersionNotSupported,
		},
	}
	for _, ts := range testSuite {
		r := chi.NewRouter()
		logger, _ := xlogger.NewLogger("info", xlogger.Config{
			LogOutputTo: []string{"stdout"},
			LoggErrsTo:  []string{"stderr"},
		}, make(map[string]interface{}))

		pnf := ts.proxyNotFound()
		r.Use(ProxyNotFoundPaths(logger, pnf))

		// Define the test route
		r.Get(ts.registeredPath, func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusOK)
		})

		req, err := http.NewRequest("GET", ts.testPath, nil)
		if err != nil {
			t.Fatal(err)
		}

		recorder := httptest.NewRecorder()
		r.ServeHTTP(recorder, req)

		assert.Equal(t, ts.statusExpected, recorder.Code)
	}
}

type mockForward struct{}

func (s *mockForward) ForwarRequest(w http.ResponseWriter, r *http.Request, _ string) {
	w.WriteHeader(http.StatusHTTPVersionNotSupported)
}
