// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package common

import (
	"net/http"

	"code.gitea.io/gitea/modules/sessiontag"
)

// SessionTagHeader is the HTTP header browser tabs use to broadcast a
// per-page-load identifier with every mutation request. The server
// echoes it back inside SSE event payloads so the originating tab
// can suppress its own event after applying the optimistic update.
const SessionTagHeader = "X-Session-Tag"

// SessionTagMiddleware decorates each incoming request's context with
// the X-Session-Tag header value when present. Service- and model-
// layer publishers read the value via sessiontag.SessionTagFromContext.
//
// Empty / missing headers are a no-op.
func SessionTagMiddleware() func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			tag := r.Header.Get(SessionTagHeader)
			if tag != "" {
				ctx := sessiontag.WithSessionTag(r.Context(), tag)
				r = r.WithContext(ctx)
			}
			next.ServeHTTP(w, r)
		})
	}
}
