package middleware

import (
	"log"
	"net/http"

	"metazone.cc/metalab/internal/common"

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

// AdminAuth 管理后台页面认证：失败时 302 跳首页而非返回 JSON
func (am *AuthMiddleware) AdminAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		sid, err := c.Cookie(common.SessionCookieName)
		if err != nil || sid == "" {
			common.ClearSessionCookie(c, am.cfg)
			c.Redirect(http.StatusFound, "/")
			c.Abort()
			return
		}

		s, err := am.sessionManager.Validate(sid)
		if err != nil || s == nil {
			log.Printf("[AdminAuth] session invalid path=%s → 302", c.Request.URL.Path)
			common.ClearSessionCookie(c, am.cfg)
			c.Redirect(http.StatusFound, "/")
			c.Abort()
			return
		}

		log.Printf("[AdminAuth] OK uid=%d role=%s path=%s", s.UserID, s.Role, c.Request.URL.Path)
		injectSessionContext(c, s)
		c.Next()
	}
}
