package catalogapp

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"time"

	"github.com/pingcap-inc/nexuscrm-contract/pkg/appauthority"
)

func newUUIDv7(now time.Time) (string, error) {
	var raw [16]byte
	if _, err := rand.Read(raw[:]); err != nil {
		return "", err
	}
	milliseconds := uint64(now.UTC().UnixMilli())
	raw[0] = byte(milliseconds >> 40)
	raw[1] = byte(milliseconds >> 32)
	raw[2] = byte(milliseconds >> 24)
	raw[3] = byte(milliseconds >> 16)
	raw[4] = byte(milliseconds >> 8)
	raw[5] = byte(milliseconds)
	raw[6] = (raw[6] & 0x0f) | 0x70
	raw[8] = (raw[8] & 0x3f) | 0x80
	encoded := hex.EncodeToString(raw[:])
	value := encoded[:8] + "-" + encoded[8:12] + "-" + encoded[12:16] + "-" + encoded[16:20] + "-" + encoded[20:]
	if err := appauthority.ValidateAppInstallationID(value); err != nil {
		return "", fmt.Errorf("mint UUIDv7: %w", err)
	}
	return value, nil
}
