package tenant

import (
	"crypto/rand"
	"encoding/hex"
	"net/http"
)

const csrfCookieName = "morz_csrf"

// setCSRFCookie setzt (oder erneuert) den CSRF-Cookie und gibt das Token zurück.
func setCSRFCookie(w http.ResponseWriter, r *http.Request, devMode bool) string {
	if c, err := r.Cookie(csrfCookieName); err == nil && c.Value != "" {
		return c.Value
	}
	buf := make([]byte, 32)
	if _, err := rand.Read(buf); err != nil {
		return ""
	}
	token := hex.EncodeToString(buf)
	http.SetCookie(w, &http.Cookie{
		Name:     csrfCookieName,
		Value:    token,
		Path:     "/",
		HttpOnly: false,
		Secure:   !devMode,
		SameSite: http.SameSiteLaxMode,
		MaxAge:   8 * 3600,
	})
	return token
}
