package server

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/rjNemo/underscore"
)

const (
	defaultTTL = 2592000 // 1 month
)

// CachingMiddleware adds caching headers.
//
// ttl is the max age of the cache in seconds. If ttl is 0, the default value will be used.
func CachingMiddleware(ttl int, fileTypes ...string) func(http.Handler) http.Handler {
	if ttl == 0 {
		ttl = defaultTTL
	}

	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			shouldCache := underscore.Any(fileTypes, func(v string) bool {
				return strings.HasSuffix(r.URL.Path, fmt.Sprintf(".%s", v))
			})

			if shouldCache {
				segments := strings.Split(r.URL.Path, "/")
				etag := segments[len(segments)-1]

				w.Header().Set("Etag", etag)
				w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", ttl))

				if match := r.Header.Get("If-None-Match"); match != "" {
					if strings.Contains(match, etag) {
						w.WriteHeader(http.StatusNotModified)
						return
					}
				}
			}

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