package httpmiddleware

import (
	"net/http"
)

// Security adds configurable security headers (CSP, X-Frame-Options, etc.)
type Security struct {
	CSP string // Content-Security-Policy; empty = omit
}

// NewSecurity creates middleware with optional CSP. Default CSP allows common CDNs and unsafe-eval for ethers.js.
func NewSecurity(csp string) *Security {
	if csp == "" {
		csp = "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://unpkg.com https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; font-src 'self' https://cdnjs.cloudflare.com; img-src 'self' data: https:; connect-src 'self'"
	}
	return &Security{CSP: csp}
}

// AddSecurityHeaders wraps next with security headers
func (s *Security) AddSecurityHeaders(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if s.CSP != "" {
			w.Header().Set("Content-Security-Policy", s.CSP)
		}
		w.Header().Set("X-Frame-Options", "DENY")
		w.Header().Set("X-Content-Type-Options", "nosniff")
		w.Header().Set("X-XSS-Protection", "1; mode=block")
		w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
		w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
		w.Header().Set("Permissions-Policy", "geolocation=(), microphone=(), camera=()")
		next.ServeHTTP(w, r)
	})
}
