package middleware

import (
	"net/http"

	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/config"
)

// SecurityHeadersMiddleware adds security headers to all HTTP responses.
// These headers help protect against common web vulnerabilities.
type SecurityHeadersMiddleware struct {
	config *config.Config
}

// NewSecurityHeadersMiddleware creates a new security headers middleware.
func NewSecurityHeadersMiddleware(config *config.Config) *SecurityHeadersMiddleware {
	return &SecurityHeadersMiddleware{
		config: config,
	}
}

// Handler wraps an http.Handler to add security headers to all responses.
func (m *SecurityHeadersMiddleware) Handler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// X-Content-Type-Options: Prevents MIME-type sniffing attacks
		// Browser will strictly follow the declared Content-Type
		w.Header().Set("X-Content-Type-Options", "nosniff")

		// X-Frame-Options: Prevents clickjacking attacks
		// DENY = page cannot be displayed in any iframe
		w.Header().Set("X-Frame-Options", "DENY")

		// X-XSS-Protection: Enables browser's built-in XSS filter
		// mode=block = block the entire page if attack is detected
		// Note: Largely superseded by CSP, but still useful for older browsers
		w.Header().Set("X-XSS-Protection", "1; mode=block")

		// Referrer-Policy: Controls how much referrer information is sent
		// strict-origin-when-cross-origin = full URL for same-origin, origin only for cross-origin
		w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")

		// Cache-Control: Prevent caching of sensitive responses
		// Especially important for auth endpoints
		w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, private")

		// Permissions-Policy: Restricts browser features (formerly Feature-Policy)
		// Disables potentially dangerous features like geolocation, camera, microphone
		w.Header().Set("Permissions-Policy", "geolocation=(), camera=(), microphone=()")

		// Content-Security-Policy: Prevents XSS and other code injection attacks
		// For API-only backend: deny all content sources and frame embedding
		w.Header().Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")

		// Strict-Transport-Security (HSTS): Forces HTTPS for the specified duration
		// Only set in production where HTTPS is properly configured
		// max-age=31536000 = 1 year in seconds
		// includeSubDomains = applies to all subdomains
		if m.config.App.Environment == "production" {
			w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
		}

		next.ServeHTTP(w, r)
	})
}
