package main

import (
	"context"
	"embed"
	"io/fs"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"

	"wails-app/internal"

	"github.com/wailsapp/wails/v2"
	"github.com/wailsapp/wails/v2/pkg/options"
	"github.com/wailsapp/wails/v2/pkg/options/assetserver"
	"github.com/wailsapp/wails/v2/pkg/options/windows"
)

//go:embed all:frontend/dist
var assets embed.FS

func main() {
	// Initialize the Gin backend (non-blocking goroutine, listens on :8888)
	internal.InitBackend()

	// Reverse proxy for /api/* requests to Gin backend (strips /api prefix)
	backendURL, _ := url.Parse("http://127.0.0.1:8888")
	proxy := httputil.NewSingleHostReverseProxy(backendURL)

	// Embedded frontend static files
	distFS, err := fs.Sub(assets, "frontend/dist")
	if err != nil {
		log.Fatal("failed to get embedded frontend:", err)
	}
	fileServer := http.FileServer(http.FS(distFS))

	// Create a handler that proxies /api to Gin, serves everything else from embed
	mux := http.NewServeMux()
	mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
		// Strip /api prefix before forwarding to Gin
		r.URL.Path = r.URL.Path[4:] // remove "/api"
		if r.URL.Path == "" {
			r.URL.Path = "/"
		}
		r.RequestURI = r.URL.RequestURI()
		proxy.ServeHTTP(w, r)
	})
	mux.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
		r.URL.Path = "/"
		r.RequestURI = "/"
		proxy.ServeHTTP(w, r)
	})
	mux.Handle("/", fileServer)

	err = wails.Run(&options.App{
		Title:     "智慧停车管理系统",
		Width:     1400,
		Height:    900,
		MinWidth:  1024,
		MinHeight: 768,
		AssetServer: &assetserver.Options{
			Assets:  assets,
			Handler: mux,
		},
		OnStartup: func(ctx context.Context) {
			log.Println("Wails app started, backend running on :8888")
		},
		Windows: &windows.Options{
			WebviewIsTransparent: false,
			WindowIsTranslucent:  false,
		},
	})

	if err != nil {
		log.Fatal(err)
	}
}
