import { getTagValue, unixNow } from "applesauce-core/helpers";
import { nanoid } from "nanoid";
import { isAddressableKind } from "nostr-tools/kinds";
import { eventPipe, skip } from "../helpers/pipeline.js";
import { ensureSingletonTag } from "../helpers/tag.js";
import { includeSingletonTag, modifyPublicTags } from "./tags.js";
import { removeSingletonTag, setSingletonTag } from "./tag/common.js";
/** An operation that removes the signature from the event template */
export function stripSignature() {
    return (draft) => {
        const newDraft = { ...draft };
        Reflect.deleteProperty(newDraft, "sig");
        return newDraft;
    };
}
/** An operation that removes the id and pubkey from the event template */
export function stripStamp() {
    return (draft) => {
        const newDraft = { ...draft };
        Reflect.deleteProperty(newDraft, "id");
        Reflect.deleteProperty(newDraft, "pubkey");
        return newDraft;
    };
}
/** An operation that updates the created_at timestamp */
export function updateCreatedAt() {
    return (draft) => ({ ...draft, created_at: unixNow() });
}
/** An operation that removes all symbols from the event */
export function stripSymbols(preserve) {
    return (draft) => {
        const newDraft = { ...draft };
        for (const symbol of Reflect.ownKeys(newDraft)) {
            if (typeof symbol !== "string" && !preserve?.includes(symbol))
                Reflect.deleteProperty(newDraft, symbol);
        }
        return newDraft;
    };
}
/** Ensures parameterized replaceable kinds have "d" tags */
export function includeReplaceableIdentifier(identifier = nanoid) {
    return (draft) => {
        if (!isAddressableKind(draft.kind))
            return draft;
        // Add a "d" tag if it doesn't exist
        if (!getTagValue(draft, "d")) {
            let tags = Array.from(draft.tags);
            const id = typeof identifier === "string" ? identifier : identifier();
            tags = ensureSingletonTag(tags, ["d", id], true);
            return { ...draft, tags };
        }
        return draft;
    };
}
/** Includes a NIP-31 alt tag in an events public tags */
export function includeAltTag(description) {
    return includeSingletonTag(["alt", description]);
}
/** Sets the NIP-40 expiration timestamp for an event */
export function setExpirationTimestamp(timestamp) {
    return includeSingletonTag(["expiration", timestamp.toString()], true);
}
/** Adds or removes the NIP-70 "-" tag from an event */
export function setProtected(set = true) {
    return modifyPublicTags(set ? setSingletonTag(["-"]) : removeSingletonTag("-"));
}
/** Creates the necessary operations for meta tag options */
export function setMetaTags(options) {
    return eventPipe(options?.protected ? setProtected(true) : skip(), options?.expiration ? setExpirationTimestamp(options.expiration) : skip(), options?.alt ? includeAltTag(options.alt) : skip());
}
