package middleware

import (
	"log"
	"net/http"
	"os"
)

func SetHeaders(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodOptions {
			// Only set Content-Type if not SSE
			if w.Header().Get("Content-Type") != "text/event-stream" {
				w.Header().Set("Content-Type", "application/json")
			}
		}

		w.Header().Set("X-DNS-Prefetch-Control", "off")
		w.Header().Set("X-Frame-Options", "DENY")
		w.Header().Set("X-XSS-Protection", "1; mode=block")
		w.Header().Set("X-Content-Type-Options", "nosniff")
		w.Header().Set("Content-Security-Policy", "default-src 'self'")
		w.Header().Set("Referrer-Policy", "no-referrer")
		w.Header().Set("X-Powered-By", "Zig")

		GoEnv := os.Getenv("GO_ENV")

		if GoEnv == "" {
			log.Fatal("GO_ENV is not set in SetHeaders middleware. Please set the GO_ENV environment variable.")
		}

		if GoEnv != "development" {
			w.Header().Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload")
		}

		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusOK)
			return
		}

		next.ServeHTTP(&FlusherPreservingResponseWriter{ResponseWriter: w}, r)
	})
}
