package middlewares

import (
	"GoMembership/internal/config"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
)

func TestCSPMiddleware(t *testing.T) {
	// Save the current environment and restore it after the test
	originalEnv := config.Env

	tests := []struct {
		name           string
		environment    string
		expectedHeader string
		expectedPolicy string
	}{
		{
			name:           "Development Environment",
			environment:    "development",
			expectedHeader: "Content-Security-Policy-Report-Only",
			expectedPolicy: "default-src 'self'; " +
				"script-src 'self' 'unsafe-inline'" +
				"style-src 'self' 'unsafe-inline'" +
				"img-src 'self'" +
				"font-src 'self'" +
				"connect-src 'self'; " +
				"frame-ancestors 'none'; " +
				"form-action 'self'; " +
				"base-uri 'self'; " +
				"upgrade-insecure-requests; report-uri /csp-report;",
		},
		{
			name:           "Production Environment",
			environment:    "production",
			expectedHeader: "Content-Security-Policy",
			expectedPolicy: "default-src 'self'; " +
				"script-src 'self' 'unsafe-inline'" +
				"style-src 'self' 'unsafe-inline'" +
				"img-src 'self'" +
				"font-src 'self'" +
				"connect-src 'self'; " +
				"frame-ancestors 'none'; " +
				"form-action 'self'; " +
				"base-uri 'self'; " +
				"upgrade-insecure-requests;",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Set up the test environment
			config.Env = tt.environment

			// Create a new Gin router with the middleware
			gin.SetMode(gin.TestMode)
			router := gin.New()
			router.Use(CSPMiddleware())
			router.GET("/test", func(c *gin.Context) {
				c.String(http.StatusOK, "test")
			})

			// Create a test request
			req, _ := http.NewRequest("GET", "/test", nil)
			w := httptest.NewRecorder()

			// Serve the request
			router.ServeHTTP(w, req)

			// Check the response
			assert.Equal(t, http.StatusOK, w.Code)
			assert.Equal(t, tt.expectedPolicy, w.Header().Get(tt.expectedHeader))
		})
	}
	config.Env = originalEnv
}
