package server

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

	"github.com/labstack/echo/v4"
	"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 wil be used.
func CachingMiddleware(ttl int, fileTypes ...string) echo.MiddlewareFunc {
	if ttl == 0 {
		ttl = defaultTTL
	}
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			shouldCache := underscore.Any(fileTypes, func(v string) bool {
				return strings.HasSuffix(c.Request().RequestURI, fmt.Sprintf(".%s", v))
			})

			if shouldCache {
				s := strings.Split(c.Request().RequestURI, "/")
				etag := s[len(s)-1]

				c.Response().Header().Set("Etag", etag)
				c.Response().Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", ttl))
				if match := c.Request().Header.Get("If-None-Match"); match != "" {
					if strings.Contains(match, etag) {
						return c.NoContent(http.StatusNotModified)
					}
				}
			}

			return next(c)
		}
	}
}
