package cors

import "net/http"

// HandlerForOrigin returns a CORS middleware function that sets headers based on the requested origin.
func HandlerForOrigin(origin string) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if o := r.Header.Get("Origin"); o != "" {
				w.Header().Set("Access-Control-Allow-Origin", origin)
				w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
				w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
				w.Header().Set("Access-Control-Expose-Headers", "Authorization")
				w.Header().Set("Access-Control-Allow-Credentials", "true")
			}
			if r.Method == "OPTIONS" {
				w.WriteHeader(http.StatusNoContent)

				return
			}
			next.ServeHTTP(w, r)
		})
	}
}

// DeafaultHandler: Returns a handler that allows requests from any origin by delegating to a handler that allows all origins.
func DeafaultHandler(next http.Handler) http.Handler {
	return HandlerForOrigin("*")(next)
}
