package httphandlers

import (
	"net/http"
	"testing"

	"github.com/fiskerinc/cloud-services/pkg/testhelper"
)

const expectedRedirectURL = "/docs/index.html"
const expectedNoRedirectURL = ""

func TestSwaggerDocsRedirect(t *testing.T) {
	type test struct {
		name             string
		request          *http.Request
		expectedRedirect string
	}

	tests := []test{
		{
			name:             "Redirect to index.html",
			request:          makeRequest("http://test.com/docs"),
			expectedRedirect: expectedRedirectURL,
		},
		{
			name:             "/ Redirect to index.html",
			request:          makeRequest("http://test.com/docs/"),
			expectedRedirect: expectedRedirectURL,
		},
		{
			name:             "Requests index.html, no redirect",
			request:          makeRequest("http://test.com/docs/index.html"),
			expectedRedirect: expectedNoRedirectURL,
		},
		{
			name:             "Requests .js, no redirect",
			request:          makeRequest("http://test.com/docs/index.js"),
			expectedRedirect: expectedNoRedirectURL,
		},
		{
			name:             "Requests .css, no redirect",
			request:          makeRequest("http://test.com/docs/index.css"),
			expectedRedirect: expectedNoRedirectURL,
		},
		{
			name:             "Requests .json, no redirect",
			request:          makeRequest("http://test.com/docs/index.json"),
			expectedRedirect: expectedNoRedirectURL,
		},
	}

	for _, item := range tests {
		path := shouldRedirect(item.request)

		if path != item.expectedRedirect {
			t.Errorf(testhelper.TestErrorTemplate, item.name, item.expectedRedirect, path)
		}
	}
}

func makeRequest(url string) *http.Request {
	request, _ := http.NewRequest(http.MethodGet, url, nil)
	request.RequestURI = url
	return request
}
