package utils

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/dgrijalva/jwt-go"
	"github.com/gofiber/fiber/v2"
	"golang.org/x/crypto/bcrypt"
)

func HashPassword(password string) ([]byte, error) {
	return bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
}

func VerifyAuthentication(c *fiber.Ctx, cookie string) (*jwt.StandardClaims, error) {

	token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(os.Getenv("API_SECRET")), nil
	})

	if err != nil {
		return nil, err
	}

	claims := token.Claims.(*jwt.StandardClaims)

	return claims, nil
}

func ProcessToken(c *fiber.Ctx) (interface{}, error) {
	bearToken := c.Get("Authorization")

	var token string

	// Normally Authorization HTTP header.
	onlyToken := strings.Split(bearToken, " ")
	if len(onlyToken) == 2 {
		token = onlyToken[1]
	} else {
		token = bearToken
	}

	tk, err := jwt.Parse(token, jwtKeyFunc)

	if err != nil {
		fmt.Println("Error 1")
		return nil, err
	}

	claims, ok := tk.Claims.(jwt.MapClaims)

	if ok && tk.Valid {
		return claims["user"], nil
	}

	return nil, err
}

func jwtKeyFunc(token *jwt.Token) (interface{}, error) {
	return []byte(os.Getenv("API_SECRET")), nil
}

func PrettyPrintJson(data interface{}) {
	b, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		fmt.Println("error:", err)
	}
	log.Println(string(b))
}
