package common

import (
	"log"
	"net/http"

	"metazone.cc/metalab/internal/config"

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

// Cookie 名称常量
const (
	CookieName        = "mlb_token"
	RefreshCookieName = "mlb_refresh"
	RMCookieName      = "mlb_rm" // 记住我标记，JS 可读
)

// SetAuthCookies 设置 access + refresh Cookie
// rememberMe=true  → Cookie 持久化（30天），关浏览器后仍保持登录
// rememberMe=false → Cookie 用 session 模式（maxAge=0），关浏览器即清除，但页面开启期间自动刷新
func SetAuthCookies(c *gin.Context, accessToken, refreshToken string, rememberMe bool, cfg *config.Config) {
	secure := cfg.Server.Mode != "debug"
	c.SetSameSite(http.SameSiteLaxMode)

	setCookie(c, CookieName, accessToken, cfg.JWT.AccessExpire*60, secure)

	if rememberMe {
		setCookie(c, RefreshCookieName, refreshToken, int(cfg.JWT.RememberExpire*3600), secure)
		setPlainCookie(c, RMCookieName, "1", int(cfg.JWT.RememberExpire*3600), secure)
	} else {
		// session cookie：关浏览器即清除，但页面开启期间自动刷新生效
		setCookie(c, RefreshCookieName, refreshToken, 0, secure)
		setPlainCookie(c, RMCookieName, "1", 0, secure)
	}
}

// SetAccessCookie 仅刷新 access Cookie（refresh 续期调用）
func SetAccessCookie(c *gin.Context, accessToken string, cfg *config.Config) {
	secure := cfg.Server.Mode != "debug"
	c.SetSameSite(http.SameSiteLaxMode)
	setCookie(c, CookieName, accessToken, cfg.JWT.AccessExpire*60, secure)
}

// ClearAuthCookies 清除所有认证 Cookie（logout 调用）
func ClearAuthCookies(c *gin.Context, cfg *config.Config) {
	secure := cfg.Server.Mode != "debug"
	c.SetCookie(CookieName, "", -1, "/", "", secure, true)
	c.SetCookie(RefreshCookieName, "", -1, "/", "", secure, true)
	c.SetCookie(RMCookieName, "", -1, "/", "", secure, false)
}

// setCookie 写入一个 HttpOnly Cookie
func setCookie(c *gin.Context, name, value string, maxAge int, secure bool) {
	log.Printf("[setCookie] name=%s maxAge=%ds secure=%v", name, maxAge, secure)
	c.SetCookie(name, value, maxAge, "/", "", secure, true)
}

// setPlainCookie 写入非 HttpOnly Cookie（JS 可读）
func setPlainCookie(c *gin.Context, name, value string, maxAge int, secure bool) {
	c.SetCookie(name, value, maxAge, "/", "", secure, false)
}
