package middlewares

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/AlchemyTelcoSolutions/callisto-so-bff/cmd/app/config"
	"github.com/AlchemyTelcoSolutions/xutils-go/xlogger"
	"github.com/go-chi/chi/v5"
	"github.com/stretchr/testify/assert"
)

func TestAllowedPaths(t *testing.T) {
	t.Parallel()

	testSuite := []struct {
		name           string
		proxyConfig    config.Proxy
		testPath       string
		statusExpected int
	}{
		{
			name: "feature_disabled",
			proxyConfig: config.Proxy{
				Paths:     map[string]string{},
				IsEnabled: false,
			},
			testPath:       "/alloweds",
			statusExpected: http.StatusOK,
		},
		{
			name: "allowed_all_endpoints",
			proxyConfig: config.Proxy{
				Paths:     map[string]string{},
				IsEnabled: true,
			},
			testPath:       "/allowed",
			statusExpected: http.StatusOK,
		},
		{
			name: "allowed_some_endpoints",
			proxyConfig: config.Proxy{
				Paths:     map[string]string{"/allowed": ""},
				IsEnabled: true,
			},
			testPath:       "/allowed/with/more",
			statusExpected: http.StatusOK,
		},
		{
			name: "allowed_some_endpoints_return_404",
			proxyConfig: config.Proxy{
				Paths:     map[string]string{"/is_allowed": ""},
				IsEnabled: true,
			},
			testPath:       "/not_allowed",
			statusExpected: http.StatusNotFound,
		},
	}
	for _, ts := range testSuite {
		r := chi.NewRouter()
		logger, _ := xlogger.NewLogger("info", xlogger.Config{
			LogOutputTo: []string{"stdout"},
			LoggErrsTo:  []string{"stderr"},
		}, make(map[string]interface{}))

		r.Use(AllowedPaths(logger, ts.proxyConfig))

		// Define the test route
		r.Get(ts.testPath, 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)
	}
}
