package auth

import (
	"fmt"
	"strings"

	errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
	"github.com/golang-jwt/jwt/v4"
)

func (s Service) ParseBearerToken(bearerToken string) (*Claims, error) {
	tokenStr := strings.Replace(bearerToken, "Bearer ", "", 1)

	return s.parseToken(tokenStr)
}

func (s Service) ParseRefreshToken(refreshToken string) (*Claims, error) {
	claims, err := s.parseToken(refreshToken)
	if err != nil {
		return nil, err
	}
	if claims.Subject != s.Config.RefreshSubject {
		return nil, fmt.Errorf(errmsg.ErrorMsgInvalidRefreshToken)
	}

	return claims, nil
}

func (s Service) parseToken(token string) (*Claims, error) {
	// https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-ParseWithClaims-CustomClaimsType
	t, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(s.Config.SignKey), nil
	})
	if err != nil {
		return nil, err
	}

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

	return nil, err
}
