package auth

import (
	"net/http"

	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

func OptionalAuth(authKey string) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var tokenFromCookie, tokenFromHeader string

		tokenFromCookie, err := ctx.Cookie(ctxRequestCookieAuthorization)
		if err == http.ErrNoCookie {
			tokenFromHeader = ctx.Request.Header.Get(ctxRequestHeaderAuthorization)
		}

		if tokenFromHeader == "" {
			tokenFromHeader = "Bearer " + tokenFromCookie
		}

		if len(tokenFromHeader) > 7 {
			token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
				if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
					return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
				}

				return []byte(authKey), nil
			})

			if err != nil || !token.Valid {
				return
			}

			if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
				if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
					ctx.Set(CtxRequestHeaderUserId, int64(uid))
				}
			}
		}
	}
}
