import { kinds } from "nostr-tools";
import { getEncryptedContent, isEncryptedContentUnlocked, lockEncryptedContent, unlockEncryptedContent, } from "./encrypted-content.js";
import { getTagValue } from "./index.js";
/** Checks if a legacy direct message content is encrypted */
export function isLegacyMessageUnlocked(event) {
    return isEncryptedContentUnlocked(event);
}
export function getLegacyMessageCorrespondent(message, self) {
    return message.pubkey === self ? getTagValue(message, "p") : message.pubkey;
}
/** Returns the receiver of a legacy direct me */
export const getLegacyMessageReceiver = getLegacyMessageCorrespondent;
/** @deprecated use {@link getLegacyMessageCorrespondent} instead */
export const getLegacyMessageCorraspondant = getLegacyMessageCorrespondent;
/** Returns the sender of a legacy direct message */
export function getLegacyMessageSender(message) {
    return message.pubkey;
}
/** Returns the parent message id of a legacy message */
export function getLegacyMessageParent(message) {
    return getTagValue(message, "e");
}
/** Checks if a legacy message is valid */
export function isValidLegacyMessage(event) {
    return (event.kind === kinds.EncryptedDirectMessage &&
        getLegacyMessageCorrespondent(event, event.pubkey) !== undefined &&
        event.content.length > 0);
}
/**
 * Returns the decrypted content of a direct message
 * @param message - The message to decrypt
 * @param self - The public key of the user
 * @param signer - The signer to use to decrypt the message
 * @returns The decrypted content of the message
 */
export async function unlockLegacyMessage(message, self, signer) {
    const cached = getEncryptedContent(message);
    if (cached)
        return cached;
    // Get the correspondent
    const correspondent = getLegacyMessageCorrespondent(message, self);
    if (!correspondent)
        throw new Error("No correspondent found");
    // Unlock the encrypted content
    return await unlockEncryptedContent(message, correspondent, signer);
}
/** Clears the cached plaintext of a direct message */
export async function lockLegacyMessage(message) {
    lockEncryptedContent(message);
}
