package webui

import (
	"embed"
	"io/fs"
	"net/http"
)

//go:embed dist
var DistFS embed.FS

var distSub, _ = fs.Sub(DistFS, "dist")

func ServeHTTP() http.Handler {
	return http.FileServer(http.FS(distSub))
}

func ServeSPA() http.Handler {
	fsHandler := http.FileServer(http.FS(distSub))
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path := r.URL.Path
		if path == "/favicon.ico" {
			w.WriteHeader(http.StatusNoContent)
			return
		}
		if path == "/" || !isStaticAsset(path) {
			data, err := DistFS.ReadFile("dist/index.html")
			if err != nil {
				http.Error(w, "not found", http.StatusNotFound)
				return
			}
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
			w.Header().Set("Pragma", "no-cache")
			w.Header().Set("Expires", "0")
			w.Write(data)
			return
		}
		w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
		fsHandler.ServeHTTP(w, r)
	})
}

func isStaticAsset(path string) bool {
	exts := []string{".js", ".css", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".woff", ".woff2", ".ttf", ".eot", ".map"}
	for _, ext := range exts {
		if len(path) > len(ext) && path[len(path)-len(ext):] == ext {
			return true
		}
	}
	return false
}
