package externaladmin

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

	"github.com/gin-gonic/gin"
)

func TestExternalAuthResponsesAlwaysDisableCachingIncludingErrors(t *testing.T) {
	gin.SetMode(gin.TestMode)
	engine := gin.New()
	RegisterExternalRoutes(engine.Group("/api/v1"), New(nil, nil, Config{}, nil), BusinessHandlers{})

	tests := []struct {
		name   string
		method string
		path   string
		body   string
	}{
		{name: "login validation error", method: http.MethodPost, path: "/api/v1/external/auth/login", body: `{}`},
		{name: "me auth error", method: http.MethodGet, path: "/api/v1/external/auth/me"},
		{name: "logout auth error", method: http.MethodPost, path: "/api/v1/external/auth/logout"},
		{name: "change password auth error", method: http.MethodPost, path: "/api/v1/external/auth/change-password", body: `{}`},
	}
	for _, testCase := range tests {
		t.Run(testCase.name, func(t *testing.T) {
			request := httptest.NewRequest(testCase.method, testCase.path, bytes.NewBufferString(testCase.body))
			request.Header.Set("Content-Type", "application/json")
			responseRecorder := httptest.NewRecorder()
			engine.ServeHTTP(responseRecorder, request)
			if responseRecorder.Code < http.StatusBadRequest {
				t.Fatalf("expected error response, status=%d body=%s", responseRecorder.Code, responseRecorder.Body.String())
			}
			if got := responseRecorder.Header().Get("Cache-Control"); got != "no-store" {
				t.Fatalf("Cache-Control = %q", got)
			}
			if got := responseRecorder.Header().Get("Pragma"); got != "no-cache" {
				t.Fatalf("Pragma = %q", got)
			}
		})
	}
}

func TestExternalAuthDoesNotExposeAppCatalogBeforeLogin(t *testing.T) {
	gin.SetMode(gin.TestMode)
	engine := gin.New()
	RegisterExternalRoutes(engine.Group("/api/v1"), New(nil, nil, Config{}, nil), BusinessHandlers{})

	request := httptest.NewRequest(http.MethodGet, "/api/v1/external/auth/apps", nil)
	responseRecorder := httptest.NewRecorder()
	engine.ServeHTTP(responseRecorder, request)
	if responseRecorder.Code != http.StatusNotFound {
		t.Fatalf("anonymous App catalog status=%d body=%s", responseRecorder.Code, responseRecorder.Body.String())
	}
}
