package middleware

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

	"hyapp-admin-server/internal/config"

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

func TestCORSAllowsAndExposesExternalCSRFHeader(t *testing.T) {
	gin.SetMode(gin.TestMode)
	engine := gin.New()
	engine.Use(CORS(config.Config{CORSAllowedOrigins: []string{"https://admin.example.com"}}))
	engine.GET("/api/v1/external/auth/me", func(c *gin.Context) { c.Status(http.StatusNoContent) })

	request := httptest.NewRequest(http.MethodOptions, "/api/v1/external/auth/me", nil)
	request.Header.Set("Origin", "https://admin.example.com")
	response := httptest.NewRecorder()
	engine.ServeHTTP(response, request)

	if response.Code != http.StatusNoContent {
		t.Fatalf("preflight status = %d", response.Code)
	}
	if !strings.Contains(response.Header().Get("Access-Control-Allow-Headers"), "X-CSRF-Token") {
		t.Fatalf("allow headers = %q", response.Header().Get("Access-Control-Allow-Headers"))
	}
	if !strings.Contains(response.Header().Get("Access-Control-Expose-Headers"), "X-CSRF-Token") {
		t.Fatalf("expose headers = %q", response.Header().Get("Access-Control-Expose-Headers"))
	}
	if response.Header().Get("Access-Control-Allow-Credentials") != "true" {
		t.Fatal("credentialed external session must be allowed")
	}
}
