package server

import (
	"fmt"
	"net/http"
	"strings"
	"time"
)

const sessionHeaderName = "X-Cursor-Session-ID"
const exposeHeadersName = "Access-Control-Expose-Headers"

func ensureSessionHeader(w http.ResponseWriter, r *http.Request) string {
	sessionKey := strings.TrimSpace(r.Header.Get(sessionHeaderName))
	if sessionKey == "" {
		sessionKey = fmt.Sprintf("csess_%d", time.Now().UnixNano())
	}
	w.Header().Set(sessionHeaderName, sessionKey)

	existing := w.Header().Get(exposeHeadersName)
	if existing == "" {
		w.Header().Set(exposeHeadersName, sessionHeaderName)
	} else if !strings.Contains(strings.ToLower(existing), strings.ToLower(sessionHeaderName)) {
		w.Header().Set(exposeHeadersName, existing+", "+sessionHeaderName)
	}

	return sessionKey
}
