package main

import (
	"strconv"
	"time"

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

var secretKey = []byte("replace-with-env-variable")

func GetToken(clientId uint32) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256,
		jwt.RegisteredClaims{
			Subject:   strconv.Itoa(int(clientId)),
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		},
	)
	return token.SignedString(secretKey)
}

func GetClientIdFromToken(token string) (uint32, error) {
	parsed, err := jwt.ParseWithClaims(token, &jwt.RegisteredClaims{}, func(t *jwt.Token) (any, error) {
		if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, jwt.ErrSignatureInvalid
		}
		return secretKey, nil
	})
	if err != nil {
		return 0, err
	}

	claims, ok := parsed.Claims.(*jwt.RegisteredClaims)
	if !ok || !parsed.Valid {
		return 0, jwt.ErrTokenInvalidClaims
	}

	id, err := strconv.ParseUint(claims.Subject, 10, 32)
	if err != nil {
		return 0, err
	}
	return uint32(id), nil
}
