// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
// SPDX-License-Identifier: Apache-2.0

package middleware

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/go-openapi/testify/v2/assert"
	"github.com/go-openapi/testify/v2/require"
)

func TestSwaggerUIMiddleware(t *testing.T) {
	var o SwaggerUIOpts
	o.EnsureDefaults()
	swui := SwaggerUI(o, nil)

	t.Run("with defaults ", func(t *testing.T) {
		req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/docs", nil)
		require.NoError(t, err)
		recorder := httptest.NewRecorder()

		swui.ServeHTTP(recorder, req)
		assert.EqualT(t, http.StatusOK, recorder.Code)

		assert.EqualT(t, "text/html; charset=utf-8", recorder.Header().Get(contentTypeHeader))
		assert.StringContainsT(t, recorder.Body.String(), fmt.Sprintf("<title>%s</title>", o.Title))
		assert.StringContainsT(t, recorder.Body.String(), fmt.Sprintf(`url: '%s',`, strings.ReplaceAll(o.SpecURL, `/`, `\/`)))
		assert.StringContainsT(t, recorder.Body.String(), swaggerLatest)
		assert.StringContainsT(t, recorder.Body.String(), swaggerPresetLatest)
		assert.StringContainsT(t, recorder.Body.String(), swaggerStylesLatest)
		assert.StringContainsT(t, recorder.Body.String(), swaggerFavicon16Latest)
		assert.StringContainsT(t, recorder.Body.String(), swaggerFavicon32Latest)
	})

	t.Run("with path with a trailing / (issue #238)", func(t *testing.T) {
		req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/docs/", nil)
		require.NoError(t, err)
		recorder := httptest.NewRecorder()

		swui.ServeHTTP(recorder, req)
		assert.EqualT(t, http.StatusOK, recorder.Code)
	})

	t.Run("should yield not found", func(t *testing.T) {
		req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/nowhere", nil)
		require.NoError(t, err)
		recorder := httptest.NewRecorder()

		swui.ServeHTTP(recorder, req)
		assert.EqualT(t, http.StatusNotFound, recorder.Code)
	})

	t.Run("edge cases", func(t *testing.T) {
		t.Run("with custom template that fails to execute", func(t *testing.T) {
			assert.Panics(t, func() {
				SwaggerUI(SwaggerUIOpts{
					Template: `<!DOCTYPE html>
<html>
	spec-url='{{ .Unknown }}'
</html>
`,
				}, nil)
			})
		})
	})
}
