package main

import (
	"context"
	"net/http"

	"git.haelnorr.com/h/golib/hws"
	"git.haelnorr.com/h/golib/hwsauth"
	"git.haelnorr.com/h/oslstats/internal/config"
	"git.haelnorr.com/h/oslstats/internal/db"
	"git.haelnorr.com/h/oslstats/pkg/contexts"

	"github.com/pkg/errors"
	"github.com/uptrace/bun"
)

func addMiddleware(
	server *hws.Server,
	auth *hwsauth.Authenticator[*db.User, bun.Tx],
	flags *config.Flags,
) error {

	err := server.AddMiddleware(
		auth.Authenticate(),
		htmxLog(flags.HTMXLog),
	)
	if err != nil {
		return errors.Wrap(err, "server.AddMiddleware")
	}
	return nil
}

func htmxLog(htmxlog bool) hws.Middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx := context.WithValue(r.Context(), contexts.HTMXLogKey, htmxlog)
			req := r.WithContext(ctx)
			next.ServeHTTP(w, req)
		},
		)
	}
}
