package msgbus

import (
	"crypto/rand"
	"fmt"
	"strconv"
	"time"

	"github.com/oklog/ulid"
	log "github.com/sirupsen/logrus"
)

// SafeParseInt64 ...
func SafeParseInt64(s string, d int64) int64 {
	n, e := strconv.ParseInt(s, 10, 64)
	if e != nil {
		return d
	}
	return n
}

// GenerateULID generates a new unique identifer
func GenerateULID() (string, error) {
	entropy := rand.Reader
	id, err := ulid.New(ulid.Timestamp(time.Now()), entropy)
	if err != nil {
		return "", fmt.Errorf("error generating ulid: %w", err)
	}

	return id.String(), nil
}

// MustGenerateULID generates a new unique identifer or fails
func MustGenerateULID() string {
	ulid, err := GenerateULID()
	if err != nil {
		log.WithError(err).Fatal("error generating ulid")
	}
	return ulid
}
