package strutil

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"

	"github.com/gookit/goutil/byteutil"
)

// Md5 Generate a 32-bit md5 string
func Md5(src any) string {
	return string(Md5Bytes(src))
}

// MD5 Generate a 32-bit md5 string
func MD5(src any) string { return Md5(src) }

// GenMd5 Generate a 32-bit md5 string
func GenMd5(src any) string { return Md5(src) }

// Md5Bytes Generate a 32-bit md5 bytes
func Md5Bytes(src any) []byte {
	return byteutil.Md5(src)
}

// ShortMd5 Generate a 16-bit md5 string. remove first 8 and last 8 bytes from 32-bit md5 string.
func ShortMd5(src any) string {
	return string(byteutil.ShortMd5(src))
}

// HashPasswd for quick hash an input password string
func HashPasswd(pwd, key string) string {
	hm := hmac.New(sha256.New, []byte(key))
	hm.Write([]byte(pwd))

	return hex.EncodeToString(hm.Sum(nil))
}

// VerifyPasswd for quick verify input password is valid
//
// - pwdMAC from db or config, generated by EncryptPasswd()
func VerifyPasswd(pwdMAC, pwd, key string) bool {
	decBts, err := hex.DecodeString(pwdMAC)
	if err != nil {
		return false
	}

	hm := hmac.New(sha256.New, []byte(key))
	hm.Write([]byte(pwd))

	return hmac.Equal(decBts, hm.Sum(nil))
}
