package main

import (
	"embed"
	"fmt"
	"log"
	"net/http"

	"zoraxy-waf/zoraxy_plugin"
)

//go:embed web/*
var webFS embed.FS

func main() {
	spec := &zoraxy_plugin.IntroSpect{
		ID:            "zoraxy-waf",
		Name:          "Zoraxy WAF",
		Author:        "Zoraxy Community",
		AuthorContact: "",
		Description:   "Web Application Firewall plugin for Zoraxy.",
		URL:           "",
		Type:          zoraxy_plugin.PluginType_Utilities,
		VersionMajor:  1,
		VersionMinor:  0,
		VersionPatch:  0,
		UIPath:        "/ui",
	}

	config, err := zoraxy_plugin.ServeAndRecvSpec(spec)
	if err != nil {
		log.Fatalf("failed to receive config: %v", err)
	}

	mux := http.NewServeMux()

	uiRouter := zoraxy_plugin.NewPluginEmbedUIRouter(
		spec.ID,
		&webFS,
		"web",
		spec.UIPath,
	)

	// Register API endpoints here.
	// Example: uiRouter.HandleFunc("/api/status", handleStatus, mux)

	uiRouter.RegisterTerminateHandler(func() {
		log.Println("zoraxy-waf shutting down")
	}, mux)

	uiRouter.AttachHandlerToMux(mux)

	addr := fmt.Sprintf("127.0.0.1:%d", config.Port)
	log.Printf("zoraxy-waf v%d.%d.%d listening on %s",
		spec.VersionMajor, spec.VersionMinor, spec.VersionPatch, addr)

	if err := http.ListenAndServe(addr, mux); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
