// +build embed

package web

import (
	"embed"
	"io"
	"io/fs"
	"net/http"
	"path/filepath"
	"strings"
)

//go:embed frontend/dist
var static embed.FS

func (s *Server) IndexHandler(frontendDir string) http.HandlerFunc {
	dir, err := fs.Sub(static, "frontend/dist")
	if err != nil {
		panic(err)
	}
	fileSrv := http.FileServer(http.FS(dir))

	fn := func(w http.ResponseWriter, r *http.Request) {
		path := strings.TrimPrefix(r.URL.Path, "/")
		_, err := dir.Open(path)
		if err != nil {
			serveIndex(frontendDir).ServeHTTP(w, r)
			return
		}
		fileSrv.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}

func serveIndex(frontendDir string) http.HandlerFunc {
	dir, err := fs.Sub(static, "frontend/dist")
	if err != nil {
		panic(err)
	}
	fn := func(w http.ResponseWriter, r *http.Request) {
		fname := filepath.Join("index.html")
		f, err := dir.Open(fname)
		if err != nil {
			panic(err)
		}
		defer f.Close()

		io.Copy(w, f)
	}
	return fn
}
