package middleware

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

	"metazone.cc/metalab/internal/config"

	"github.com/gin-gonic/gin"
)

const csrfTokenLen = 32

// SetCSRFToken 在首次页面访问时下发 CSRF Cookie（由页面路由中间件调用）
func SetCSRFToken(c *gin.Context, cfg *config.Config) string {
	secure := cfg.Server.Mode != "debug"
	if existing, err := c.Cookie(csrfCookieName); err == nil && existing != "" {
		c.Set(csrfMetaName, existing)
		return existing
	}

	token, err := generateCSRFToken()
	if err != nil {
		token = "fallback-" + hex.EncodeToString([]byte("metazone"))
	}

	c.SetSameSite(http.SameSiteStrictMode)
	maxAge := cfg.Session.RememberTimeout * 60
	c.SetCookie(csrfCookieName, token, maxAge, "/", "", secure, false)
	c.Set(csrfMetaName, token)
	return token
}

// generateCSRFToken 生成 64 字符十六进制随机 CSRF token
func generateCSRFToken() (string, error) {
	b := make([]byte, csrfTokenLen)
	if _, err := rand.Read(b); err != nil {
		return "", err
	}
	return hex.EncodeToString(b), nil
}


