import { createHash } from "node:crypto";
import { customAlphabet } from "nanoid";

//#region src/utils/conversations.ts
const generateId = customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789", 21);
/**
* Derive a deterministic 32-character hex ID from natural key parts.
* Used for junction/relation table IDs so the same logical relation
* always produces the same ID regardless of which branch creates it.
*/
function deriveRelationId(...parts) {
	return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
}
/**
* Generates a standardized conversation ID.
*
* The generated ID follows these rules:
* 1. Always lowercase
* 2. No leading hyphens
*
* @returns A unique conversation ID
*
* @example
* ```typescript
* const id = getConversationId(); // returns something like "v1stgxr8z5jdhi6bmyt"
* ```
*/
function getConversationId() {
	return generateId();
}
function buildConversationMetadata(executionContext, _userProperties) {
	const meta = executionContext.metadata;
	const isAuthenticated = meta?.authMethod === "app_credential_web_client_authenticated";
	const result = {};
	if (meta?.verifiedClaims) result.verifiedClaims = meta.verifiedClaims;
	if (isAuthenticated && meta?.endUserId) result.externalUserId = meta.endUserId;
	if (meta?.initiatedBy) result.initiatedBy = meta.initiatedBy;
	return Object.keys(result).length > 0 ? result : void 0;
}
function getConversationUserProperties(c) {
	return c.userProperties ?? null;
}
function getConversationProperties(c) {
	return c.properties ?? null;
}
function getMessageUserProperties(m, c) {
	if (m.userProperties != null) return m.userProperties;
	return c ? getConversationUserProperties(c) : null;
}
function buildConversationUserProperties(_executionContext, userProperties) {
	return userProperties ?? void 0;
}

//#endregion
export { buildConversationMetadata, buildConversationUserProperties, deriveRelationId, generateId, getConversationId, getConversationProperties, getConversationUserProperties, getMessageUserProperties };