package model

import (
	"encoding/base64"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/rs/zerolog/log"
)

type AuthToken struct {
	SignedToken string `json:"jwt"`
	token       jwt.Token
}

type TokenGenerationError struct {
	message string
}

func (e *TokenGenerationError) Error() string {
	return e.message
}

// Create a struct to hold your custom claims
type customClaims struct {
	Username string `json:"username"`
	jwt.StandardClaims
}

const signingKey = "nDjYmTjoPrAGzuyhHz6Dq5bqcRrEZJc5Ls3SQcdylBI="

func NewAuthToken(username string) (*AuthToken, error) {
	claims := customClaims{
		Username: username,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Hour * 24 * 5).Unix(), // 5 days
		},
	}

	// Create a new JWT token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	if token == nil {
		log.Error().Msg("Error creating Jwt Token")
		return nil, &TokenGenerationError{"Error creating Jwt Token"}
	}

	// Sign the token with the specified signing key
	decodedSigningKey, _ := base64.StdEncoding.DecodeString(signingKey)
	signedToken, err := token.SignedString(decodedSigningKey)
	if err != nil {
		log.Error().Err(err).Msg("Error signing Jwt Token")
		return nil, &TokenGenerationError{"Error signing Jwt Token"}
	}

	return &AuthToken{
		SignedToken: signedToken,
		token:       *token,
	}, nil
}
