package middleware

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

	"kra/internal/conf"

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

func runCORSTest(t *testing.T, admin *conf.AdminBackend, method, origin string) *httptest.ResponseRecorder {
	t.Helper()
	engine := gin.New()
	engine.Use(CORS(conf.NewRuntime(nil, admin)))
	engine.Any("/test", func(c *gin.Context) { c.Status(http.StatusOK) })
	request := httptest.NewRequest(method, "/test", nil)
	if origin != "" {
		request.Header.Set("Origin", origin)
	}
	response := httptest.NewRecorder()
	engine.ServeHTTP(response, request)
	return response
}

func TestCORSDoesNotConsumeUnmatchedWhitelistPreflight(t *testing.T) {
	response := runCORSTest(t, &conf.AdminBackend{Cors: &conf.AdminBackend_CORS{Mode: "whitelist"}}, http.MethodOptions, "https://unknown.example")
	if response.Code != http.StatusOK {
		t.Fatalf("unmatched whitelist preflight status = %d, want %d", response.Code, http.StatusOK)
	}
}

func TestCORSConsumesMatchedWhitelistPreflight(t *testing.T) {
	response := runCORSTest(t, &conf.AdminBackend{Cors: &conf.AdminBackend_CORS{Mode: "whitelist", Whitelist: []*conf.AdminBackend_CORSRule{{AllowOrigin: "https://admin.example"}}}}, http.MethodOptions, "https://admin.example")
	if response.Code != http.StatusNoContent {
		t.Fatalf("matched whitelist preflight status = %d, want %d", response.Code, http.StatusNoContent)
	}
}

func TestCORSStrictWhitelistAllowsPrefixedHealth(t *testing.T) {
	if !isHealthPath("/admin/health") {
		t.Fatal("prefixed health endpoint was not recognized by strict whitelist")
	}
}
