package middlewares

import (
	"bpmsapi/util"
	"fmt"

	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt"
)

func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		const BEARER_SCHEMA = "Bearer:"
		authHeader := c.GetHeader("Authorization")
		var tokenString string
		if strings.Contains(authHeader, "Bearer") && len(authHeader) > len(BEARER_SCHEMA) {
			tokenString = authHeader[len(BEARER_SCHEMA):]
		} else {
			c.AbortWithStatusJSON(http.StatusUnauthorized, "JWT Token is Empty")
			return
		}
		fmt.Println(tokenString)
		token, err := util.JWTAuthService().ValidateToken(tokenString)
		//fmt.Println(err.Error())
		//Token is expired - Error message for Token expired
		if err != nil {
			if err.Error() == "Token is expired" {
				c.Next()
				claims := token.Claims.(jwt.MapClaims)
				var emailId string
				var isAdmin bool
				emailId, _ = claims["email"].(string)
				isAdmin, _ = claims["is_admin"].(bool)
				jwtToken := util.JWTAuthService().GenerateToken(string(emailId), isAdmin)
				util.FormatResult(c, &jwtToken)
			} else {
				mess := fmt.Sprint("JWT Token Invalid with error ", err.Error())
				c.AbortWithStatusJSON(http.StatusUnauthorized, mess)
				return
			}
		} else {
			if token.Valid {
				claims := token.Claims.(jwt.MapClaims)
				c.Next()
				util.FormatResult(c, nil)
				fmt.Println(claims)
			} else {
				mess := fmt.Sprint("JWT Token Invalid with error", err.Error())
				c.AbortWithStatusJSON(http.StatusUnauthorized, mess)
				return
			}
		}

	}
}
