package main

import (
	"context"
	"homepage/antispam"
	"log/slog"
	"net"
	"net/http"
	"os"
	"path"

	"github.com/AlessandroSechi/zammad-go"
)

type rootPathKey struct{}
type zammadKey struct{}

func getRootPath(r *http.Request) string {
	if rootPath, ok := r.Context().Value(rootPathKey{}).(string); ok {
		return rootPath
	}
	panic("missing root path in request context")
}

func main() {
	slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		Level: slog.LevelDebug,
	})))

	rootPath := path.Clean("../dist")
	slog.Info("Found root path for static assets", "path", rootPath)

	var zammadClient *zammad.Client
	if zammadUrl := os.Getenv("ZAMMAD_URL"); zammadUrl != "" {
		zammadClient = zammad.New(zammadUrl)
		token := os.Getenv("ZAMMAD_TOKEN")
		if token == "" {
			slog.Error("No Zammad token available, set ZAMMAD_TOKEN accordingly")
			os.Exit(1)
		}
		slog.Info("Using Zammad integration", "url", zammadUrl)
		zammadClient.Token = token
	} else {
		slog.Warn("Zammad integration disabled, set ZAMMAD_URL to enable")
	}

	mux := http.NewServeMux()

	setupSite(mux)
	mux.Handle("/", http.FileServer(http.Dir(rootPath)))

	var handler http.Handler
	handler = ProtectCsrf(mux, []byte("fasdf"))
	handler = antispam.WithAntispam(handler)

	server := http.Server{
		Addr:    "localhost:8080",
		Handler: handler,
		BaseContext: func(_ net.Listener) context.Context {
			ctx := context.Background()
			ctx = context.WithValue(ctx, rootPathKey{}, rootPath)
			if zammadClient != nil {
				ctx = context.WithValue(ctx, zammadKey{}, zammadClient)
			}
			return ctx
		},
	}

	slog.Info("Starting HTTP server", "addr", server.Addr)
	if err := server.ListenAndServe(); err != nil {
		slog.Error("Failed to start HTTP server", "error", err)
	}
}
