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) {
		claims, err := am.authenticateToken(c)
		if err != nil {
			log.Printf("[AdminAuth] auth failed path=%s err=%v → 302", c.Request.URL.Path, err)
			common.ClearAuthCookies(c, am.cfg)
			c.Redirect(http.StatusFound, "/")
			c.Abort()
			return
		}
		log.Printf("[AdminAuth] OK: uid=%v role=%v path=%s", claims["uid"], claims["role"], c.Request.URL.Path)
		injectUserContext(c, claims)
		c.Next()
	}
}
