package static

import (
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

func Handler(dir string, fallback http.Handler) http.Handler {
	if strings.TrimSpace(dir) == "" {
		return fallback
	}
	fs := http.FileServer(http.Dir(dir))
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if strings.HasPrefix(r.URL.Path, "/api/") {
			fallback.ServeHTTP(w, r)
			return
		}
		path := filepath.Join(dir, filepath.Clean(r.URL.Path))
		if info, err := os.Stat(path); err == nil && !info.IsDir() {
			fs.ServeHTTP(w, r)
			return
		}
		http.ServeFile(w, r, filepath.Join(dir, "index.html"))
	})
}
