package auth

import (
	"net/http"
	"strings"

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

const CurrentUserIDKey = "currentUserID"

func RequireUser(tokenVerifier func(string) (uint, error)) gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Request.Method == http.MethodPost && c.Request.URL.Path == "/api/v1/auth/login" {
			c.Next()
			return
		}

		header := c.GetHeader("Authorization")
		token := strings.TrimPrefix(header, "Bearer ")
		if token == "" || token == header {
			abortWithError(c, http.StatusUnauthorized, "missing_bearer_token", "请先登录后再操作")
			return
		}
		userID, err := tokenVerifier(token)
		if err != nil {
			abortWithError(c, http.StatusUnauthorized, "invalid_bearer_token", "登录状态无效或已过期，请重新登录")
			return
		}
		c.Set(CurrentUserIDKey, userID)
		c.Next()
	}
}

// 认证包不能反向依赖路由包；此处保持与 httpx.Error 相同的安全错误边界。
func abortWithError(c *gin.Context, status int, code, message string) {
	c.AbortWithStatusJSON(status, gin.H{
		"error": gin.H{"code": code, "message": message},
	})
}

func CurrentUserID(c *gin.Context) (uint, bool) {
	value, ok := c.Get(CurrentUserIDKey)
	if !ok {
		return 0, false
	}
	userID, ok := value.(uint)
	return userID, ok && userID > 0
}
