package utils

import (
	"errors"
	"time"

	"git.echol.cn/loser/st/server/global"
	"github.com/golang-jwt/jwt/v5"
)

const (
	UserTypeApp = "app" // 前台用户类型标识
)

// AppJWTClaims 前台用户 JWT Claims
type AppJWTClaims struct {
	UserID   uint   `json:"userId"`
	Username string `json:"username"`
	UserType string `json:"userType"` // 用户类型标识
	jwt.RegisteredClaims
}

// CreateAppToken 创建前台用户 Token（有效期 7 天）
func CreateAppToken(userID uint, username string) (tokenString string, expiresAt int64, err error) {
	// Token 有效期为 7 天
	expiresTime := time.Now().Add(7 * 24 * time.Hour)
	expiresAt = expiresTime.Unix()

	claims := AppJWTClaims{
		UserID:   userID,
		Username: username,
		UserType: UserTypeApp,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expiresTime),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Issuer:    global.GVA_CONFIG.JWT.Issuer,
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err = token.SignedString([]byte(global.GVA_CONFIG.JWT.SigningKey))
	return
}

// CreateAppRefreshToken 创建前台用户刷新 Token（有效期更长）
func CreateAppRefreshToken(userID uint, username string) (tokenString string, expiresAt int64, err error) {
	// 刷新 Token 有效期为 7 天
	expiresTime := time.Now().Add(7 * 24 * time.Hour)
	expiresAt = expiresTime.Unix()

	claims := AppJWTClaims{
		UserID:   userID,
		Username: username,
		UserType: UserTypeApp,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expiresTime),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Issuer:    global.GVA_CONFIG.JWT.Issuer,
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err = token.SignedString([]byte(global.GVA_CONFIG.JWT.SigningKey))
	return
}

// ParseAppToken 解析前台用户 Token
func ParseAppToken(tokenString string) (*AppJWTClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &AppJWTClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(global.GVA_CONFIG.JWT.SigningKey), nil
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*AppJWTClaims); ok && token.Valid {
		return claims, nil
	}

	return nil, errors.New("invalid token")
}
