package middlewares

import (
	"GoMembership/internal/config"
	"GoMembership/pkg/logger"
	"net/http"

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

func CSPMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		policy := "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;"

		if config.Env == "development" {
			policy += " report-uri /csp-report;"
			c.Header("Content-Security-Policy-Report-Only", policy)
		} else {
			c.Header("Content-Security-Policy", policy)
		}
		c.Next()
	}
}

func CSPReportHandling(c *gin.Context) {
	var report map[string]interface{}
	if err := c.BindJSON(&report); err != nil {

		logger.Error.Printf("Couldn't Bind JSON: %#v", err)
		return
	}
	logger.Info.Printf("CSP Violation: %+v", report)
	c.Status(http.StatusNoContent)
}
