package server

import (
	"encoding/json"
	"log/slog"
	"net/http"

	"github.com/pingcap/agent-git-service/internal/tenant"
)

func tenantResolutionMiddleware(resolver tenantResolver) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			resolution := resolver.resolve(r)
			if !resolution.OK {
				slog.WarnContext(r.Context(), "tenant resolution rejected request",
					"tenant_resolution_source", resolution.Source,
					"tenant_resolution_reason", resolution.Reason,
				)
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusMisdirectedRequest)
				_ = json.NewEncoder(w).Encode(map[string]string{
					"message": "request host is not configured for this service",
				})
				return
			}

			ctx := tenant.WithInfo(r.Context(), resolution.Tenant)
			ctx = tenant.WithResolvedHost(ctx, resolution.Host)
			next.ServeHTTP(w, r.WithContext(ctx))
		})
	}
}
