package middleware

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

	"kra/internal/config"

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

func runCORSTest(t *testing.T, admin *config.Admin, method, origin string) *httptest.ResponseRecorder {
	t.Helper()
	engine := gin.New()
	engine.Use(CORS(config.NewStore(&config.Config{Admin: 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, &config.Admin{CORS: &config.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, &config.Admin{CORS: &config.CORS{Mode: "whitelist", Whitelist: []*config.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")
	}
}
