package lib

import (
	"crypto/sha256"
	"encoding/binary"
	"fmt"
	"path/filepath"
	"strconv"

	"github.com/google/uuid"
)

// NewID generates a new int64 ID by partial-hashing a UUID.
func NewID() int64 {
	u := uuid.New()
	h := sha256.Sum256(u[:])
	return int64(binary.BigEndian.Uint64(h[:8]) & 0x7FFFFFFFFFFFFFFF)
}

// IDToHex converts an int64 ID to a 16-char lowercase hex string.
func IDToHex(id int64) string {
	return fmt.Sprintf("%016x", id)
}

// HexToID parses a 16-char hex string into an int64 ID.
func HexToID(s string) (int64, error) {
	if len(s) != 16 {
		return 0, fmt.Errorf("invalid id: must be 16 hex chars, got %d", len(s))
	}
	v, err := strconv.ParseUint(s, 16, 64)
	if err != nil {
		return 0, fmt.Errorf("invalid id: %w", err)
	}
	return int64(v), nil
}

// VaultDBPath returns the path to a vault's SQLite file.
// Filename is the upper 32 bits of vault_id as 8-char hex.
func VaultDBPath(dataDir string, vaultID int64) string {
	return filepath.Join(dataDir, fmt.Sprintf("%08x.db", uint32(vaultID>>32)))
}
