package common

import (
	"log"
	"net/http"

	"metazone.cc/metalab/internal/config"

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

// Cookie 名称常量
const (
	SessionCookieName = "mlb_sid" // 会话 ID Cookie（HttpOnly）
)

// SetSessionCookie 写入会话 ID Cookie
// rememberMe=true → Cookie 持久化（30天），关浏览器后仍保持登录
// rememberMe=false → Cookie session 模式（maxAge=0），关浏览器即清除
func SetSessionCookie(c *gin.Context, sid string, rememberMe bool, cfg *config.Config) {
	secure := cfg.Server.Mode != "debug"
	c.SetSameSite(http.SameSiteLaxMode)

	var maxAge int
	if rememberMe {
		maxAge = cfg.Session.RememberTimeout * 60 // 分钟 → 秒
	} else {
		maxAge = 0 // session cookie
	}

	log.Printf("[SetSessionCookie] sid=%s rememberMe=%v maxAge=%ds secure=%v", sid[:16]+"...", rememberMe, maxAge, secure)
	c.SetCookie(SessionCookieName, sid, maxAge, "/", "", secure, true)
}

// ClearSessionCookie 清除会话 ID Cookie（logout 调用）
func ClearSessionCookie(c *gin.Context, cfg *config.Config) {
	secure := cfg.Server.Mode != "debug"
	c.SetCookie(SessionCookieName, "", -1, "/", "", secure, true)
}

