package httpserver

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

func (s *Server) appFileServer() http.Handler {
	if s.config.Web.DevViteURL != "" {
		viteURL, err := url.Parse(s.config.Web.DevViteURL)
		if err == nil {
			proxy := httputil.NewSingleHostReverseProxy(viteURL)
			originalDirector := proxy.Director
			proxy.Director = func(req *http.Request) {
				originalDirector(req)
				req.Host = viteURL.Host
				// Add back the /app/ prefix that was stripped by http.StripPrefix
				req.URL.Path = "/app" + req.URL.Path
			}
			return proxy
		}
	}

	files := http.FileServer(http.Dir(s.config.Web.DistDir))
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		cleanPath := filepath.Clean(strings.TrimPrefix(r.URL.Path, "/"))
		if cleanPath == "." {
			cleanPath = "index.html"
		}

		target := filepath.Join(s.config.Web.DistDir, cleanPath)
		if info, err := os.Stat(target); err == nil && !info.IsDir() {
			files.ServeHTTP(w, r)
			return
		}

		http.ServeFile(w, r, filepath.Join(s.config.Web.DistDir, "index.html"))
	})
}
