package middleware

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

func CORSMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		origins := os.Getenv("CORS_ORIGINS")
		if origins == "" {
			// Strict default: only allow exact matches or specific development origin if needed.
			// For this project, we prefer configuration.
			origins = "http://localhost:3000"
		}

		origin := r.Header.Get("Origin")
		allowOrigin := ""

		// Check if the origin is allowed
		if origins == "*" {
			allowOrigin = "*"
		} else {
			for _, o := range strings.Split(origins, ",") {
				if strings.TrimSpace(o) == origin {
					allowOrigin = origin
					break
				}
			}
		}

		if allowOrigin != "" {
			w.Header().Set("Access-Control-Allow-Origin", allowOrigin)
		}

		// Essential for some auth flows (cookies)
		w.Header().Set("Access-Control-Allow-Credentials", "true")

		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")
		w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

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

		next.ServeHTTP(w, r)
	})
}
