package middleware

import (
	"log"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

// parseToken 解析并验证 JWT
func parseToken(tokenStr, secret string) (jwt.MapClaims, error) {
	now := time.Now()
	token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	})
	if err != nil || !token.Valid {
		log.Printf("[parseToken] FAIL: now=%v err=%v (secret_len=%d token_len=%d)",
			now, err, len(secret), len(tokenStr))
		return nil, err
	}
	claims, ok := token.Claims.(jwt.MapClaims)
	if !ok {
		return nil, jwt.ErrSignatureInvalid
	}
	if exp, exists := claims["exp"]; exists {
		var expTime time.Time
		switch v := exp.(type) {
		case float64:
			expTime = time.Unix(int64(v), 0)
		case *jwt.NumericDate:
			expTime = v.Time
		}
		if !expTime.IsZero() {
			log.Printf("[parseToken] OK: exp=%v (%d) now=%v isExpired=%v",
				expTime, expTime.Unix(), now, now.After(expTime))
		}
	}
	return claims, nil
}

// IsLoginPage 检查是否已在登录状态，已登录用户跳过登录/注册页
func IsLoginPage(c *gin.Context) bool {
	return strings.HasPrefix(c.Request.URL.Path, "/auth/")
}
