package middleware

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"

	"mengyaping-backend/models"
	"mengyaping-backend/storage"
)

// AdminAuth 校验管理员令牌：环境变量 ADMIN_TOKEN 优先，否则使用 MySQL monitor_kv 中的 admin_token（请求头 X-Admin-Token 或 Authorization: Bearer）
func AdminAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		expected := storage.GetStorage().EffectiveAdminToken()
		if expected == "" {
			c.AbortWithStatusJSON(http.StatusServiceUnavailable, models.APIResponse{
				Code:    503,
				Message: "未配置管理员令牌：请在数据库 monitor_kv 写入 admin_token，或设置环境变量 ADMIN_TOKEN",
			})
			return
		}

		got := strings.TrimSpace(c.GetHeader("X-Admin-Token"))
		if got == "" {
			auth := c.GetHeader("Authorization")
			const prefix = "Bearer "
			if len(auth) >= len(prefix) && strings.EqualFold(auth[:len(prefix)], prefix) {
				got = strings.TrimSpace(auth[len(prefix):])
			}
		}

		if got == "" || got != expected {
			c.AbortWithStatusJSON(http.StatusUnauthorized, models.APIResponse{
				Code:    401,
				Message: "无效的管理员令牌",
			})
			return
		}
		c.Next()
	}
}
