package middleware

import (
	"net/http"
)

// SecurityHeaders sets safe default response headers (OWASP guidance).
// Content-Security-Policy stays permissive (API serves JSON/CSV only) but
// clickjacking, MIME sniffing and referrer leakage are blocked.
func SecurityHeaders(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		h := w.Header()
		h.Set("X-Content-Type-Options", "nosniff")
		h.Set("X-Frame-Options", "DENY")
		h.Set("Referrer-Policy", "no-referrer")
		h.Set("X-XSS-Protection", "1; mode=block")
		h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
		next.ServeHTTP(w, r)
	})
}

// BodyLimit rejects requests with a known Content-Length above maxBytes (413)
// before the handler runs, and guards chunked/unknown-length bodies with
// http.MaxBytesReader so the handler surfaces a *http.MaxBytesError. maxBytes
// <= 0 disables the limit.
func BodyLimit(maxBytes int64) func(http.Handler) http.Handler {
	if maxBytes <= 0 {
		return func(next http.Handler) http.Handler { return next }
	}
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.ContentLength > maxBytes {
				w.Header().Set("Connection", "close")
				http.Error(w, "request body too large", http.StatusRequestEntityTooLarge)
				return
			}
			r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
			next.ServeHTTP(w, r)
		})
	}
}
