import type { Readable } from 'node:stream';
import type { WaAbPropName } from '../../abprops-spec';
import type { WaMessageDispatchCoordinator } from '../coordinators/WaMessageDispatchCoordinator';
import type { WaTrustedContactTokenCoordinator } from '../coordinators/WaTrustedContactTokenCoordinator';
import { type WaUploadMediaSource } from '../media';
import { type UploadResult, type WaMediaMessageOptions } from '../messaging/messages';
import type { WaDownloadMediaOptions, WaIncomingAddonEvent, WaIncomingMessageEvent, WaSendMessageOptions } from '../types';
import type { Logger } from '../../infra/log/types';
import type { WaMediaTransferClient } from '../../media/transfer/WaMediaTransferClient';
import type { MediaKind } from '../../media/types';
import type { WaMediaRetryRequest, WaMediaRetryRequester, WaMediaRetryResult } from '../../message/primitives/media-retry';
import type { PeerDataOperationRequester } from '../../message/primitives/peer-data-operation';
import type { WaMessagePublishResult, WaSendMessageContent, WaSendReceiptEventOptions, WaSendReceiptOptions } from '../../message/types';
import { type Proto } from '../../proto';
import type { WaMessageSecretStore } from '../../store/contracts/message-secret.store';
import type { WaMessageStore } from '../../store/contracts/message.store';
import { type WaMexQuerySocket } from '../../transport/node/mex/client';
export interface WaMessageCoordinatorDeps {
    readonly messageDispatch: WaMessageDispatchCoordinator;
    readonly mediaTransfer: WaMediaTransferClient;
    /** Backs {@link WaMessageCoordinator.requestMediaReupload}. */
    readonly mediaRetry: WaMediaRetryRequester;
    /** Media upload wiring shared with the send path; backs {@link WaMessageCoordinator.upload}. */
    readonly mediaUploadOptions: WaMediaMessageOptions;
    readonly logger: Logger;
    readonly messageStore: WaMessageStore;
    readonly messageSecretStore: WaMessageSecretStore;
    readonly trustedContactToken: WaTrustedContactTokenCoordinator;
    readonly emitAddon: (event: WaIncomingAddonEvent) => void;
    readonly mexSocket: WaMexQuerySocket;
    readonly peerDataOperation: PeerDataOperationRequester;
    /**
     * Server-synced `group_history_send` AB-prop. WhatsApp gates the sender
     * side per account, and rejects the stanza with SMAX_INVALID when it is
     * off, so {@link WaMessageCoordinator.shareGroupHistory} checks it before
     * spending an upload.
     */
    readonly isGroupHistorySendEnabled: () => boolean;
    /**
     * Reads a server-synced numeric AB-prop, falling back to its shipped
     * default. Sole source for the group-history message-count limit, so a
     * server-side change takes effect without a release.
     */
    readonly getAbPropNumber: (name: WaAbPropName) => number;
}
export interface WaShareGroupHistoryInput {
    /**
     * Members to share the history with. Must be current members of the group,
     * written in the group's own addressing mode - a LID-addressed group only
     * matches `@lid` entries, and a PN one only matches `@s.whatsapp.net`.
     * Anything else throws, naming the mode the group uses. Read the mode off
     * `client.group.queryGroupMetadata()`, whose participants carry both forms.
     */
    readonly toJids: readonly string[];
    /**
     * How many of the most recent messages to read from the mailbox store.
     * Defaults to WhatsApp's `group_history_message_count_limit` (100).
     * Ignored when {@link messages} is supplied - that list is bundled as-is.
     */
    readonly count?: number;
    /**
     * Only read messages at or after this timestamp (ms) from the mailbox
     * store. Ignored when {@link messages} is supplied.
     */
    readonly sinceMs?: number;
    /**
     * Messages to bundle, bypassing the mailbox store entirely - {@link count}
     * and {@link sinceMs} do not apply, so the caller owns the windowing.
     * Required when the `messages` store domain is `'none'` (the default),
     * since there is nothing to read back in that case.
     */
    readonly messages?: readonly Proto.IWebMessageInfo[];
    /**
     * Pinned messages older than the shared window. The receiver injects these
     * regardless of the age cutoff it applies to `messages`.
     */
    readonly outOfWindowPinnedMessages?: readonly Proto.IWebMessageInfo[];
}
export interface WaShareGroupHistoryResult {
    /** Stanza id of the bundle message, fanned out only to `historyReceivers`. */
    readonly bundleMessageId: string;
    /**
     * Stanza id of the notice message, sent to the whole group. Absent when the
     * notice failed to send: the bundle still reached its receivers, so do not
     * retry the share - it would upload and deliver the history a second time.
     */
    readonly noticeMessageId?: string;
    readonly messagesCount: number;
    readonly historyReceivers: readonly string[];
    readonly nonHistoryReceivers: readonly string[];
}
export interface WaRequestHistorySyncInput {
    /** Chat the older messages should be fetched from. */
    readonly chatJid: string;
    /**
     * Id of the oldest message currently in the local view. The server
     * pages backwards from this anchor. Omit to let the server pick its
     * own anchor (rarely useful).
     */
    readonly oldestMsgId?: string;
    /** Whether {@link oldestMsgId} was sent by the current account. */
    readonly oldestMsgFromMe?: boolean;
    /** Epoch ms of the oldest local message; pairs with {@link oldestMsgId}. */
    readonly oldestMsgTimestampMs?: number;
    /**
     * How many older messages to request. WhatsApp Web defaults to the
     * server-side `history_sync_on_demand_message_count` AB-prop (~50);
     * passing nothing here leaves the field unset so the server applies
     * its own default.
     */
    readonly count?: number;
}
export interface WaReachoutTimelock {
    readonly isActive: boolean;
    readonly enforcementType: string | null;
    readonly enforcementEndsAt: number | null;
}
export type WaMessageCappingType = 'INDIVIDUAL_NEW_CHAT_THREAD';
export interface WaMessageCappingInfo {
    readonly totalQuota: number | null;
    readonly usedQuota: number | null;
    readonly cycleStartAt: number | null;
    readonly cycleEndAt: number | null;
    readonly serverSentAt: number | null;
    readonly oteStatus: string | null;
    readonly mvStatus: string | null;
    readonly cappingStatus: string | null;
}
/**
 * Media kinds accepted by {@link WaMessageCoordinator.upload}. `gif` is a
 * GIF-playback video, `ptt` a voice note, `ptv` a round video note.
 */
export type WaUploadMediaType = MediaKind | 'gif' | 'ptt';
/** Options for {@link WaMessageCoordinator.upload}. */
export interface WaUploadMediaOptions {
    /** Media type: sets the encryption context and CDN upload path. */
    readonly type: WaUploadMediaType;
    /** `Content-Type` for the upload and the mimetype for the message proto. */
    readonly mimetype?: string;
    /** Reuse a 32-byte media key instead of generating one. */
    readonly mediaKey?: Uint8Array;
    /** Override the streaming sidecar (default on for video/ptv/audio/gif/ptt). */
    readonly sidecar?: boolean;
    /** Animated-sticker first-frame length for the first-frame sidecar. */
    readonly firstFrameLength?: number;
    /** Per-upload transfer timeout override (ms). */
    readonly timeoutMs?: number;
    /** Cancellation signal forwarded to the CDN request. */
    readonly signal?: AbortSignal;
}
/**
 * Reusable descriptor returned by {@link WaMessageCoordinator.upload}: the
 * {@link UploadResult} fields plus the media-key timestamp and echoed mimetype.
 */
export interface WaMediaUploadResult extends UploadResult {
    /** Unix seconds the media key was minted; belongs on the message proto. */
    readonly mediaKeyTimestamp: number;
    /** Echo of the `mimetype` option when provided. */
    readonly mimetype?: string;
}
/**
 * Coordinates outbound message sending, receipts, addon decryption, media
 * upload/download, and the related MEX account queries. Accessed via
 * {@link WaClient.message}.
 */
export declare class WaMessageCoordinator {
    private readonly messageDispatch;
    private readonly mediaTransfer;
    private readonly mediaRetry;
    private readonly mediaUploadOptions;
    private readonly logger;
    private readonly messageStore;
    private readonly messageSecretStore;
    private readonly trustedContactToken;
    private readonly emitAddon;
    private readonly mexSocket;
    private readonly peerDataOperation;
    private readonly isGroupHistorySendEnabled;
    private readonly getAbPropNumber;
    constructor(deps: WaMessageCoordinatorDeps);
    /**
     * Asks the server to backfill older messages for `chatJid` beyond what
     * arrived in the initial history-sync. Implemented as a
     * `PeerDataOperationRequestMessage` (type `HISTORY_SYNC_ON_DEMAND`)
     * sent to this account's own user JID; the response arrives later as
     * a `history_sync_chunk` event the same way the bootstrap chunks do -
     * subscribe before calling if you need to react to the chunk.
     *
     * The method returns once the request is dispatched (with the protocol
     * message id), **not** when the chunk arrives. Pair `oldestMsgId` +
     * `oldestMsgTimestampMs` + `oldestMsgFromMe` from the topmost message
     * currently visible to page backwards correctly.
     */
    requestHistorySync(input: WaRequestHistorySyncInput): Promise<{
        readonly messageId: string;
    }>;
    /**
     * Shares recent group history with members who joined after the fact - the
     * counterpart of the `group_history_bundle` event on the receiving side.
     *
     * Sends two messages: the bundle itself, encrypted per device and fanned
     * out **only** to `toJids` (never to the whole group), followed by a hidden
     * notice addressed to everyone so other clients can render the "history was
     * shared" marker.
     *
     * WhatsApp gates the sender side per account through the `group_history_send`
     * AB-prop and rejects the stanza with SMAX_INVALID when it is off, so this
     * throws up front rather than spending an upload. Admin-only groups
     * (`memberShareGroupHistoryMode: 'admin_share'`) reject a share from a
     * regular member server-side - read `client.group.queryGroupMetadata()`
     * first if you want to check that too.
     *
     * @throws when the account is not allowed to share group history, when
     * `groupJid` is not a group, when any of `toJids` is not a current member
     * (or is this account), or when there is nothing to bundle.
     * @example
     * ```ts
     * await client.message.shareGroupHistory('12036@g.us', {
     *     toJids: ['5511999999999@s.whatsapp.net'],
     *     count: 50
     * })
     * ```
     */
    shareGroupHistory(groupJid: string, input: WaShareGroupHistoryInput): Promise<WaShareGroupHistoryResult>;
    /**
     * Reads the most recent messages of a group back out of the mailbox store
     * and rebuilds the `WebMessageInfo` shape a bundle carries. Yields nothing
     * when the `messages` store domain is `'none'`.
     */
    private loadGroupHistoryMessages;
    /**
     * Fetches the server-side "reachout" timelock that throttles cold outreach
     * to non-contacts, returning the active window when enforcement is on.
     */
    getReachoutTimelock(): Promise<WaReachoutTimelock>;
    /**
     * Fetches the per-cycle message capping info applied to new-chat threads
     * (quota, used, cycle boundaries, status flags).
     */
    getNewChatMessageCapping(type?: WaMessageCappingType): Promise<WaMessageCappingInfo>;
    /**
     * Force-refreshes the Signal session(s) for `jid`. Set `reasonIdentity` to
     * `true` when the trigger was an identity change – this also queues a
     * trusted-contact-token reissue.
     */
    syncSignalSession(jid: string, reasonIdentity?: boolean): Promise<void>;
    /**
     * Sends a message (any {@link WaSendMessageContent} kind – text, media,
     * poll, reaction, edit, revoke, etc.) to `to` and returns the publish
     * result containing the stanza id and ack metadata.
     *
     * `to` accepts any JID accepted by {@link normalizeRecipientJid}: bare
     * digits (`'5511999999999'`), a phone JID (`'5511…@s.whatsapp.net'`),
     * a group JID (`'…@g.us'`), or a LID. See the {@link WaSendMessageContent}
     * union for the full kind list.
     *
     * **Gotchas:**
     * - The stanza id is auto-generated unless you set `options.id`. Reusing
     *   an id manually makes the send idempotent on the server but is also how
     *   internal retries (`maxAttempts`) work – don't reuse ids across
     *   logically distinct messages.
     * - Sending to a `@newsletter` JID routes through a separate code path
     *   that ignores most of `options` (no quote/forward/edit semantics).
     * - Addon-crypto kinds (poll-vote, reaction, message-edit, ...) require an
     *   authenticated session (`meJid` present) – throws otherwise.
     * - Group sends fan out to every cached member device. If your
     *   `groupMetadata` cache is empty/disabled, this triggers a metadata IQ
     *   per send (rate-limited server-side, see {@link WaCreateStoreOptions}).
     *
     * @example
     * ```ts
     * // 1. Plain text (string shorthand)
     * await client.message.send('5511999999999', 'hello!')
     *
     * // 2. Reply with mention
     * await client.message.send(groupJid, {
     *     type: 'text',
     *     text: '@5511999999999 ping',
     *     contextInfo: {
     *         mentionedJid: ['5511999999999@s.whatsapp.net'],
     *         quoted: { key: { remoteJid: groupJid, fromMe: false, id: incomingId } }
     *     }
     * })
     *
     * // 3. Image from a file path (the encoder opens + streams it for you)
     * await client.message.send(jid, {
     *     type: 'image',
     *     media: '/tmp/photo.jpg',
     *     mimetype: 'image/jpeg',
     *     caption: 'check this out'
     * })
     *
     * // 4. React to an incoming message (empty emoji = unreact)
     * await client.message.send(event.key.remoteJid, {
     *     type: 'reaction',
     *     emoji: '👍',
     *     target: event.key // or pass the whole event
     * })
     *
     * // 5. Poll
     * const result = await client.message.send(jid, {
     *     type: 'poll',
     *     name: 'lunch?',
     *     options: ['pizza', 'sushi', 'burger'],
     *     selectableCount: 1
     * })
     * console.log('sent as', result.id)
     * ```
     */
    send(to: string, content: WaSendMessageContent, options?: WaSendMessageOptions): Promise<WaMessagePublishResult>;
    /**
     * Sends a receipt (delivery / read / played / inactive). Overloads:
     * - Pass one or many `WaIncomingMessageEvent` to auto-derive chat/sender
     *   metadata and batch ids by chat.
     * - Pass an explicit `(jid, ids, options)` triple for manual control.
     *
     * **You usually don't need to call this for `'delivery'`** - the library
     * already auto-ACKs delivery on every incoming `<message>` it decrypts
     * successfully. Use this manually for `'read'`/`'played'` (read receipts
     * the user explicitly toggled) or for `'inactive'`/retry receipts.
     */
    sendReceipt(target: WaIncomingMessageEvent | readonly WaIncomingMessageEvent[], options?: WaSendReceiptEventOptions): Promise<void>;
    sendReceipt(jid: string, ids: string | readonly string[], options?: WaSendReceiptOptions): Promise<void>;
    /**
     * Encrypts and uploads standalone media to the WhatsApp CDN and returns the
     * reusable descriptor, without sending a message - pre-upload once and
     * reference it across sends, or build custom protos. Needs a connected
     * session (the host token comes from a `media_conn` IQ). `source` is bytes,
     * a file path, or a `Readable`. To send the result, spread its fields onto
     * the matching proto message and pass that to {@link send}.
     *
     * @throws when `source` is unsupported, the file is unreadable, or the upload fails.
     * @example
     * ```ts
     * const media = await client.message.upload(await readFile('photo.jpg'), {
     *     type: 'image',
     *     mimetype: 'image/jpeg'
     * })
     * await client.message.send(jid, {
     *     imageMessage: {
     *         url: media.url,
     *         directPath: media.directPath,
     *         mediaKey: media.mediaKey,
     *         fileSha256: media.fileSha256,
     *         fileEncSha256: media.fileEncSha256,
     *         fileLength: media.fileLength,
     *         mediaKeyTimestamp: media.mediaKeyTimestamp,
     *         mimetype: media.mimetype
     *     }
     * })
     * ```
     */
    upload(source: WaUploadMediaSource, options: WaUploadMediaOptions): Promise<WaMediaUploadResult>;
    /**
     * Resolves the media payload inside `source` and returns a `Readable`
     * stream of the decrypted bytes. Throws when the message has no
     * downloadable media.
     *
     * **Caller owns the stream** - pipe it somewhere or call `.destroy()` to
     * release the underlying socket; an unconsumed stream leaks the connection.
     * MAC + SHA-256 verification runs **as bytes are consumed**, so if you
     * abort mid-read you've consumed unverified bytes. Pass `options.signal`
     * to cancel cleanly, or use {@link downloadBytes} / {@link downloadToFile}
     * for one-shot verified downloads.
     */
    download(source: WaIncomingMessageEvent | Proto.IMessage, options?: WaDownloadMediaOptions): Promise<Readable>;
    /**
     * Convenience wrapper around {@link download} that streams the decrypted
     * media directly to `filePath`. On failure the **partial file is not
     * cleaned up** - delete it yourself in the error handler if you don't
     * want to leak corrupted artifacts.
     */
    downloadToFile(source: WaIncomingMessageEvent | Proto.IMessage, filePath: string, options?: WaDownloadMediaOptions): Promise<void>;
    /**
     * Convenience wrapper around {@link download} that buffers the decrypted
     * media into a single `Uint8Array`. Use only for small media – caps via
     * `options.maxBytes`.
     */
    downloadBytes(source: WaIncomingMessageEvent | Proto.IMessage, options?: WaDownloadMediaOptions): Promise<Uint8Array>;
    /**
     * Asks the sender's primary device to re-upload a message's media, for when
     * the CDN answers `404`/`410` because the blob expired - typically old
     * media surfaced by a history sync. Sends a `server-error` receipt carrying
     * the sealed request and resolves once the server answers with a
     * `mediaretry` notification, usually within a couple of seconds.
     *
     * On `result: 'success'` the media key, hashes, and length of the original
     * message normally stay valid, so patch the fresh `directPath` into the
     * message and download again. A second call for a message already in
     * flight joins the first request instead of sending another receipt.
     *
     * A `success` is not a guarantee that the original key still opens the
     * blob. Some primaries re-encrypt the file on every re-upload, and the
     * re-served bytes then fail `fileEncSha256` and make `downloadBytes()`
     * throw a MAC mismatch. Nothing in the round-trip carries key material for
     * the new ciphertext, so the message cannot be recovered through this API
     * and requesting another reupload will not help.
     *
     * The other three `result` values are answers too, not thrown errors:
     * `not_found` means the sender no longer holds the file and nothing can
     * recover it, `decryption_error` that it could not open its own copy, and
     * `general_error` anything else including a result code this version does
     * not recognize.
     *
     * Requires the message's media key, so it only works for media you received
     * or sent, never for a bare message id. Newsletter messages are rejected -
     * channel media has no per-message key to seal the request with. Pass an
     * explicit `WaMediaRetryRequest` instead of an event when you hold the
     * message id, chat jid, and media key but not the decoded message.
     *
     * @throws when the message carries no downloadable media, is a newsletter
     * message, the session is not paired, the stanza cannot be sent, or no
     * notification arrives before `options.timeoutMs`. It does **not** throw on
     * a `not_found` / `general_error` answer - check `result`.
     * @example
     * ```ts
     * const image = event.message?.imageMessage
     * try {
     *     return await client.message.downloadBytes(event)
     * } catch {
     *     const retry = await client.message.requestMediaReupload(event)
     *     if (retry.result !== 'success') throw new Error(`reupload ${retry.result}`)
     *     return await client.message.downloadBytes({
     *         imageMessage: { ...image, directPath: retry.directPath }
     *     })
     * }
     * ```
     */
    requestMediaReupload(event: WaIncomingMessageEvent, options?: {
        readonly timeoutMs?: number;
    }): Promise<WaMediaRetryResult>;
    requestMediaReupload(request: WaMediaRetryRequest): Promise<WaMediaRetryResult>;
    /**
     * Attempts to decrypt an addon payload (poll vote, reaction, edit, ...)
     * attached to `event` and, on success, emits a typed
     * `WaIncomingAddonEvent`. Silently returns when the parent message
     * secret is missing or the payload is not an addon.
     *
     * Called automatically by the client unless `options.addons.autoDecrypt`
     * is explicitly `false` - you rarely need to invoke it directly. The
     * parent secret is looked up in the in-memory `messageSecret` cache
     * first, then in the `messages` store. If both are `'none'`/missing,
     * decryption fails and the event never fires; failures are logged at
     * `warn` for `secretEncryptedMessage` addons (whose parent can be
     * any message type, so the secret is only available when the
     * `messages` mailbox is active) and at `debug` for the dedicated
     * addon types (reactions, poll votes, event responses, comments)
     * whose parent always carries a persisted secret or is itself
     * short-lived.
     */
    tryDecryptAddon(event: WaIncomingMessageEvent): Promise<void>;
    private dispatchReceipt;
}
