package utils

import (
	"fmt"
	"os"
	"strconv"
	"time"

	"ems-backend/models"

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

type Claims struct {
	Username string `json:"username"`
	UserID   string `json:"userId"`
	jwt.RegisteredClaims
}

func jwtSecret() []byte {
	secret := os.Getenv("JWT_SECRET")
	if secret == "" {
		secret = "ems-dev-secret"
	}
	return []byte(secret)
}

func tokenExpireHours() int {
	expireStr := os.Getenv("JWT_EXPIRE_HOURS")
	if expireStr == "" {
		return 24
	}
	expireHours, err := strconv.Atoi(expireStr)
	if err != nil || expireHours <= 0 {
		return 24
	}
	return expireHours
}

func GenerateToken(user models.User) (string, error) {
	now := time.Now()
	expiresAt := now.Add(time.Duration(tokenExpireHours()) * time.Hour)

	claims := Claims{
		Username: user.Username,
		UserID:   user.ID.String(),
		RegisteredClaims: jwt.RegisteredClaims{
			IssuedAt:  jwt.NewNumericDate(now),
			ExpiresAt: jwt.NewNumericDate(expiresAt),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtSecret())
}

func ParseToken(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(t *jwt.Token) (interface{}, error) {
		if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method")
		}
		return jwtSecret(), nil
	})
	if err != nil {
		return nil, err
	}
	claims, ok := token.Claims.(*Claims)
	if !ok || !token.Valid {
		return nil, fmt.Errorf("invalid token")
	}
	return claims, nil
}

