package static

import (
	"crypto/sha256"
	"embed"
	"encoding/hex"
	"net/http"
	"strings"
	"time"
)

//go:embed css/* js/* fonts/*
var staticFS embed.FS

// Version is set via -ldflags in production
var Version string

func init() {
	if Version == "" {
		h := sha256.Sum256([]byte(time.Now().String()))
		Version = hex.EncodeToString(h[:4])
	}
}

func VersionedPath(path string) string {
	return "/static/" + Version + "/" + path
}

func Handler() http.Handler {
	fileServer := http.FileServer(http.FS(staticFS))
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path := r.URL.Path
		path = strings.TrimPrefix(path, "/static/")
		if idx := strings.Index(path, "/"); idx != -1 {
			path = path[idx+1:]
		}
		r.URL.Path = "/" + path

		w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
		fileServer.ServeHTTP(w, r)
	})
}
