Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

51.0 KB
Raw Blame
/**
 * Request and response type definitions for the OpenWA API.
 *
 * IMPORTANT (hybrid codegen strategy): this module is the single source of truth
 * for wire types. It is the part most prone to drift with the backend, and is
 * structured so that it can be regenerated by an OpenAPI codegen pass later
 * without touching the hand-written resource methods (paths + DX live elsewhere).
 *
 * Field names mirror the backend DTOs exactly (camelCase JSON).
 *
 * @packageDocumentation
 */

// ── Common ────────────────────────────────────────────────────────

/** A WhatsApp JID, e.g. `[email protected]` (user) or `120363…@g.us` (group). */
export type Jid = string;

/** Chat/message kind discriminator. */
export type ChatKind = 'individual' | 'group' | 'channel' | 'status' | 'broadcast' | 'unknown';

/** Session lifecycle status. */
export type SessionStatus =
  'created' | 'initializing' | 'qr_ready' | 'authenticating' | 'ready' | 'disconnected' | 'action_required' | 'failed';

/** Minimal success envelope returned by some state-changing endpoints. */
export interface SuccessResult {
  success: boolean;
  message?: string;
}

/** One entry per requested participant, in the order they were requested. */
export interface ParticipantResult {
  /** Neutral participant id the outcome belongs to. */
  id: string;
  /**
   * True only when the engine confirmed the change for this participant. Engines that confirm the
   * batch rather than each member report one success entry per requested id, so `true` does not
   * always mean the engine spoke about that participant individually.
   */
  success: boolean;
  /** The engine's own status code, when it gave one. */
  status?: number;
  /** Engine-reported reason, when it gave one. */
  message?: string;
}

/**
 * The group membership writes. A partial refusal does NOT fail the batch — the request answers 200
 * and reports the per-participant outcome here, so `success` alone hides a member that was rejected.
 */
export interface ParticipantsResult {
  success: boolean;
  message: string;
  results: ParticipantResult[];
}

// ── Session ───────────────────────────────────────────────────────

export interface SessionResponse {
  id: string;
  name: string;
  status: SessionStatus;
  phone?: string | null;
  pushName?: string | null;
  connectedAt?: string | null;
  lastActive?: string | null;
  createdAt: string;
  updatedAt: string;
  /**
   * Human-readable reason while `status` is `'failed'` or `'action_required'`, or `'initializing'` from the
   * fifth attempt of a reconnect the engine runs itself (Baileys), or while a reconnect waits to retry after a
   * failed relaunch (either engine); `null` otherwise.
   */
  lastError?: string | null;
  /**
   * A limit WhatsApp itself has placed on the account, or `null` when there is none. Distinct from
   * `lastError`, which describes a fault on the gateway's side. Absent from a gateway that predates
   * the field.
   */
  restriction?: AccountRestriction | null;
  /**
   * Whether the gateway holds a live engine for this session: an engine in the answering process
   * or, in a multi-node deployment, a live claim by the node running it. On the node running the
   * session, `true` means `stop`, `logout` and `force-kill` can act and `start` is refused. For a
   * session another node runs, those routes act only when request routing (`NODE_URL` on every
   * node) forwards them; without it, other nodes answer 409 to `start` and `stop` and 400 to
   * `logout` and `force-kill`. Not derivable from `status`: `disconnected` covers both a session
   * mid automatic-reconnect (engine present) and one stopped with no engine. Absent from a gateway
   * that predates the field.
   */
  engineLoaded: boolean;
}

/**
 * A restriction WhatsApp has in force on a session's account.
 *
 * `reachout_timelock` leaves the session connected and existing chats working — only starting new
 * conversations is blocked — whereas `tos_block` and `proxy_block` refuse the connection itself and
 * therefore cannot coexist with a `ready` status.
 */
export interface AccountRestriction {
  kind: 'reachout_timelock' | 'tos_block' | 'proxy_block';
  /** The engine's own token for the cause, verbatim (`TOS_BLOCK`, `BIZ_QUALITY`, …). */
  code: string;
  /** ISO timestamp when enforcement ends, when WhatsApp states one. */
  expiresAt?: string | null;
}

/** One participant's presence within a chat. */
export interface ParticipantPresence {
  id: string;
  /** `composing`/`recording` mean actively typing or recording; `paused` means they stopped. */
  state: 'available' | 'unavailable' | 'composing' | 'recording' | 'paused';
  /** Unix SECONDS. Absent whenever the contact's privacy settings hide last-seen — the common case. */
  lastSeen?: number;
}

/** The last presence reported for a chat since it was subscribed. */
export interface ChatPresence {
  chatId: string;
  participants: ParticipantPresence[];
  /** Online member count, groups only. */
  groupOnlineCount?: number;
  /** When the gateway received the report — NOT a WhatsApp timestamp. */
  observedAt: string;
}

/**
 * A label create-or-update body. The id travels in the path, because WhatsApp keys the write on it.
 */
export interface UpsertLabelRequest {
  /** Not preserved when left out: the write replaces the whole label. */
  name?: string;
  /**
   * WhatsApp's colour INDEX (0-19), NOT a hex value — it does not round-trip with the `hexColor`
   * labels are read back with, because neither engine exposes the mapping. Not preserved when
   * left out either.
   */
  color?: number;
}

/** Body for creating a channel. */
export interface CreateChannelRequest {
  name: string;
  description?: string;
}

/** Body for muting or unmuting a channel. */
export interface MuteChannelRequest {
  /** True mutes, false unmutes. The subscription is unaffected either way. */
  mute: boolean;
}

/**
 * What an invite code discloses about a group before joining. Not `GroupInfo`: a non-member has no
 * participant list, only a count, and only when WhatsApp discloses one.
 */
export interface GroupJoinInfo {
  id: string;
  name: string;
  description?: string;
  owner?: string;
  /** Unix seconds. */
  createdAt?: number;
  participantCount?: number;
}

/**
 * A session's effective runtime configuration.
 *
 * Only `maxReconnectAttempts` is nullable, and `null` there means UNLIMITED — not "unset". The
 * server always reports a concrete `reconnectBaseDelay` and `autoRejectCalls`.
 */
export interface SessionConfig {
  /** Baileys only: whatsapp-web.js stores the flag but cannot reject a call, so calls keep ringing there. */
  autoRejectCalls: boolean;
  maxReconnectAttempts: number | null;
  reconnectBaseDelay: number;
}

/**
 * Partial update of a session's config. Applies to a session that is already running — no re-link and
 * no QR scan. Send `null` for `maxReconnectAttempts` to restore unlimited retries, which no in-range
 * number can express.
 */
export interface UpdateSessionConfigRequest {
  /** Baileys only: whatsapp-web.js stores the flag but cannot reject a call, so calls keep ringing there. */
  autoRejectCalls?: boolean | null;
  maxReconnectAttempts?: number | null;
  reconnectBaseDelay?: number | null;
}

/** Masked per-session proxy configuration — credentials are never returned. */
export interface SessionProxy {
  enabled: boolean;
  proxyType: 'http' | 'https' | 'socks4' | 'socks5' | null;
  proxyHost: string | null;
  hasCredentials: boolean;
}

/** Update per-session proxy settings. Send `proxyUrl: null` to clear. Applies on the next start. */
export interface UpdateSessionProxyRequest {
  proxyUrl?: string | null;
}

export interface CreateSessionRequest {
  /** Alphanumeric + hyphens, 3–50 chars. */
  name: string;
  config?: Record<string, unknown>;
  proxyUrl?: string;
  /** @deprecated Ignored by the gateway; the `proxyUrl` scheme selects the protocol. */
  proxyType?: 'http' | 'https' | 'socks4' | 'socks5';
}

export interface QrCodeResponse {
  /** Data URL, e.g. `data:image/png;base64,…`. */
  qrCode: string;
  status: SessionStatus;
}

export interface PairingCodeResponse {
  /** 8-character code, e.g. `ABCD1234`. */
  pairingCode: string;
  status: string;
}

export interface RequestPairingCodeRequest {
  /** Digits only, international format, e.g. `628123456789`. */
  phoneNumber: string;
}

export interface SessionStatsOverview {
  total: number;
  active: number;
  ready: number;
  disconnected: number;
  byStatus: Record<string, number>;
  memoryUsage: { heapUsed: number; heapTotal: number; rss: number };
}

// ── Message ───────────────────────────────────────────────────────

/** Returned by every send operation. */
export interface MessageResponse {
  messageId: string;
  /** Unix timestamp in seconds. */
  timestamp: number;
}

export interface SendTextRequest {
  chatId: Jid;
  /** Max 4096 chars. */
  text: string;
  /** WIDs to @mention (e.g. `["[email protected]"]`). The text must also contain the `@<number>` token. */
  mentions?: string[];
  /**
   * Controls the URL preview. `false` suppresses it on both engines. Otherwise the engines differ:
   * whatsapp-web.js builds one in-page by default, while on Baileys a preview is OPT-IN — it needs
   * `true`, because generating one is a blocking outbound fetch per URL.
   */
  linkPreview?: boolean;
  /**
   * Attach a preview you supply yourself instead of one fetched from the URL. Nothing is fetched, so
   * this works even for a URL the gateway cannot reach. **Baileys only** — whatsapp-web.js takes a
   * boolean and answers 501. Cannot be combined with `linkPreview: false`.
   */
  customLinkPreview?: { url: string; title: string; description?: string };
  /**
   * Quote an earlier message, turning this send into a reply. Engine-specific: whatsapp-web.js
   * matches the serialized message id, Baileys the raw message key id of a message it has already
   * stored. An id the engine cannot resolve fails the send rather than delivering it unquoted.
   */
  quotedMessageId?: string;
}

export interface SendMediaRequest {
  chatId: Jid;
  /** Mutually exclusive with `base64`. */
  url?: string;
  /** Requires `mimetype`. */
  base64?: string;
  mimetype?: string;
  /**
   * Shown only on document sends; defaults to `file` when omitted (whatsapp-web.js first tries the URL basename).
   * Max 255 chars.
   */
  filename?: string;
  /** Max 1024 chars. */
  caption?: string;
  /**
   * Quote an earlier message, turning this send into a reply. Engine-specific: whatsapp-web.js
   * matches the serialized message id, Baileys the raw message key id of a message it has already
   * stored. An id the engine cannot resolve fails the send rather than delivering it unquoted.
   */
  quotedMessageId?: string;
  /** WIDs to @mention; the caption must also contain the @<number> token. */
  mentions?: string[];
}

export interface SendAudioRequest extends SendMediaRequest {
  /** Audio only: send as a WhatsApp voice note (PTT). Server defaults mimetype to audio/ogg; codecs=opus. */
  ptt?: boolean;
}

/** Nested media payload accepted by bulk sends; chatId lives on the parent and caption on content. */
export interface BulkMediaRequest {
  url?: string;
  base64?: string;
  mimetype?: string;
  filename?: string;
  /** Only the audio member consumes this flag. */
  ptt?: boolean;
}

export interface SendLocationRequest {
  chatId: Jid;
  latitude: number;
  longitude: number;
  description?: string;
  address?: string;
  /**
   * Quote an earlier message, turning this send into a reply. Engine-specific: whatsapp-web.js
   * matches the serialized message id, Baileys the raw message key id of a message it has already
   * stored. An id the engine cannot resolve fails the send rather than delivering it unquoted.
   */
  quotedMessageId?: string;
}

export interface SendContactRequest {
  chatId: Jid;
  contactName: string;
  contactNumber: string;
  /**
   * Quote an earlier message, turning this send into a reply. Engine-specific: whatsapp-web.js
   * matches the serialized message id, Baileys the raw message key id of a message it has already
   * stored. An id the engine cannot resolve fails the send rather than delivering it unquoted.
   */
  quotedMessageId?: string;
}

export interface ReplyMessageRequest {
  chatId: Jid;
  quotedMessageId: string;
  text: string;
  /** WIDs to @mention (e.g. `["[email protected]"]`). The text/caption must also contain the `@<number>` token. */
  mentions?: string[];
}

export interface ClickButtonRequest {
  chatId: Jid;
  /** WhatsApp id of the business prompt that offered the buttons. */
  messageId: string;
  /** Stable id of the choice (inbound `buttons[].id`). */
  buttonId: string;
  /** Visible label; resolved from the stored prompt when omitted. */
  text?: string;
}

export interface ForwardMessageRequest {
  fromChatId: Jid;
  toChatId: Jid;
  messageId: string;
}

export interface ReactMessageRequest {
  chatId: Jid;
  messageId: string;
  /** Empty string removes the reaction. */
  emoji: string;
}

export interface DeleteMessageRequest {
  chatId: Jid;
  messageId: string;
  /** Delete for everyone (default true). */
  forEveryone?: boolean;
}

/** Pin windows WhatsApp recognises, in seconds: 24h, 7d, 30d. */
export type PinDurationSeconds = 86400 | 604800 | 2592000;

export interface PinMessageRequest {
  chatId: Jid;
  messageId: string;
  /** Defaults to 86400 (24h) server-side. */
  durationSeconds?: PinDurationSeconds;
}

export interface SetGroupPictureRequest {
  /** Provide exactly one of `url` or `base64` (base64 wins when both are present). */
  url?: string;
  base64?: string;
  /** Required when using `base64`. Must be an image type. */
  mimetype?: string;
}

export interface UpsertContactRequest {
  /** The contact's first name. */
  firstName: string;
  /** Omit for a single-name contact. */
  lastName?: string;
}

export interface ArchiveChatRequest {
  chatId: Jid;
  /** true to archive, false to unarchive. */
  archive: boolean;
}

export interface PinChatRequest {
  chatId: Jid;
  /** true to pin the chat to the top of the list, false to unpin it. */
  pin: boolean;
}

export interface MuteChatRequest {
  chatId: Jid;
  /**
   * Absolute epoch **milliseconds** at which the mute expires, or `null` to unmute now.
   *
   * Milliseconds, not seconds — a seconds-scale value is an instant in 1970, so the mute expires
   * immediately while the request still answers 200 and nothing in the response says otherwise.
   * Required rather than optional because the two readings of an omitted value, unmute now and mute
   * indefinitely, are opposites.
   */
  muteUntil: number | null;
}

export interface VotePollRequest {
  chatId: Jid;
  /** The poll creation message to vote on. */
  pollMessageId: string;
  /**
   * Option TEXTS to select, exactly as they appear on the poll — there are no option ids.
   * Replaces the current selection; an empty array clears the vote.
   */
  options: string[];
}

export interface StarMessageRequest {
  chatId: Jid;
  messageId: string;
  /** true to star, false to remove the star. */
  star: boolean;
}

export interface UnpinMessageRequest {
  chatId: Jid;
  messageId: string;
}

export interface EditMessageRequest {
  chatId: Jid;
  messageId: string;
  /** New text body; max 4096 chars (same cap as a send). Own messages only — 404 if not found. */
  body: string;
  /** WIDs to @mention. An edit REPLACES the body, so tags are re-applied rather than preserved. */
  mentions?: string[];
}

export interface SendTemplateRequest {
  chatId: Jid;
  /** Provide exactly one of `templateId` or `templateName`. */
  templateId?: string;
  /** Provide exactly one of `templateId` or `templateName`. */
  templateName?: string;
  /** Template variables (server DTO field is `vars`). */
  vars?: Record<string, string>;
  /** WIDs to @mention (e.g. `["[email protected]"]`). The text/caption must also contain the `@<number>` token. */
  mentions?: string[];
  /** Controls the URL preview on the rendered body, with the same engine split as `send-text`. */
  linkPreview?: boolean;
}

export interface SendPollRequest {
  chatId: Jid;
  /** Poll question / title (max 255 chars). */
  name: string;
  /** Options to vote on (WhatsApp allows between 2 and 12). */
  options: string[];
  /** Allow voters to pick several options (default single choice). */
  allowMultipleAnswers?: boolean;
  /**
   * Quote an earlier message, turning this send into a reply. Engine-specific: whatsapp-web.js
   * matches the serialized message id, Baileys the raw message key id of a message it has already
   * stored. An id the engine cannot resolve fails the send rather than delivering it unquoted.
   */
  quotedMessageId?: string;
}

export interface ListMessagesQuery {
  type?: MessageType;
  /** Inclusive message-time lower bound, Unix epoch milliseconds. */
  since?: number;
  /** Exclusive message-time upper bound, Unix epoch milliseconds. */
  until?: number;
  direction?: MessageDirection;
  /** Newest first; timestamp excludes rows without known message time. Default createdAt. */
  orderBy?: 'createdAt' | 'timestamp';
  /** Exact WhatsApp message reference within the selection. */
  messageId?: string;
  chatId?: Jid;
  from?: Jid;
  limit?: number;
  offset?: number;
  /** Keyset cursor: the `id` of the last message of the previous page. Takes precedence over `offset`. */
  after?: string;
  /** Set false to omit inline media payloads. The budget is per response, so a walk repays it per page. */
  inlineMedia?: boolean;
}

export interface MessageHistoryQuery {
  limit?: number;
  includeMedia?: boolean;
  deep?: boolean;
}

/** Message direction. */
export type MessageDirection = 'incoming' | 'outgoing';

/** Delivery status for a message. */
export type DeliveryStatus = 'pending' | 'sent' | 'delivered' | 'read' | 'failed';

/** A persisted message row, as returned by `GET /sessions/:id/messages`. */
export interface MessageRecord {
  id: string;
  sessionId: string;
  /** Engine/WhatsApp message id; may be null until a send is acked. */
  waMessageId?: string | null;
  chatId: Jid;
  from: Jid;
  to: Jid;
  body?: string | null;
  type: string;
  direction: MessageDirection;
  /**
   * Push name of the sender as the engine reported it (their saved contact name when it reported no push
   * name); in a group this is the member who posted, not the group subject. Null when no name was known.
   */
  chatName?: string | null;
  /**
   * JID of the sender of a group, status or broadcast-list message (`from` is the group, `status@broadcast`
   * or the list id there; on Baileys a received list message is filed under the sender, so `from` is the
   * sender too). Null on 1:1 messages and outgoing echoes.
   */
  author?: string | null;
  /** Storage key of the archived media copy, when chat-media archiving wrote one. */
  mediaPath?: string | null;
  /** Mimetype of the archived media; null whenever `mediaPath` is. */
  mediaMimetype?: string | null;
  /** Unix timestamp in seconds. */
  timestamp?: number | null;
  metadata?: Record<string, unknown> | null;
  status: DeliveryStatus;
  createdAt: string;
}

/**
 * The engine-normalized message kinds — persisted rows, `message.received`/`message.sent`
 * payloads and the websocket all use these values (raw engine tokens are normalized at the
 * adapter boundary).
 */
export type MessageType =
  | 'text'
  | 'image'
  | 'video'
  | 'audio'
  | 'voice'
  | 'document'
  | 'sticker'
  | 'location'
  | 'contact'
  | 'poll'
  | 'call'
  | 'revoked'
  | 'order'
  | 'product'
  | 'masked'
  | 'unknown';

/**
 * A message read live from WhatsApp by `messages.history()`. This is the engine
 * payload (richer and differently shaped than the persisted {@link MessageRecord}).
 */
export interface ChatHistoryMessage {
  id: string;
  from: Jid;
  to: Jid;
  chatId: Jid;
  body: string;
  type: MessageType;
  /** Unix timestamp in seconds. */
  timestamp: number;
  fromMe: boolean;
  isGroup: boolean;
  isStatusBroadcast?: boolean;
  kind: ChatKind;
  /** Disappearing-messages timer on the chat, in seconds. Absent when the chat has none set. */
  ephemeralDuration?: number;
  /** For group messages, the participant who sent it (`from` is the group JID). */
  author?: Jid;
  mentionedIds?: Jid[];
  /** Present on `call` messages only. */
  call?: { video: boolean; missed: boolean };
  isLidSender?: boolean;
  senderPhone?: string | null;
  /**
   * Sender contact info, best-effort from the engine's cache. History carries `name` and `pushName`;
   * the richer fields are added when `WEBHOOK_CONTACT_DETAILS=true`, as on `message.received`.
   */
  contact?: {
    id?: Jid;
    number?: string;
    name?: string;
    pushName?: string;
    shortName?: string;
    type?: string;
    isMyContact?: boolean;
    isWAContact?: boolean;
    isBusiness?: boolean;
    isEnterprise?: boolean;
    verifiedName?: string;
    verifiedLevel?: number;
    isBlocked?: boolean;
    labels?: string[];
  };
  /** Status/story styling. Declared by the engine payload; this route never sets either. */
  backgroundColor?: string;
  font?: number;
  media?: {
    mimetype: string;
    filename?: string;
    /** base64; absent when the payload was omitted (too large). */
    data?: string;
    omitted?: boolean;
    sizeBytes?: number;
  };
  quotedMessage?: { id: string; body: string };
  poll?: { name: string; options: string[]; allowMultipleAnswers: boolean };
  location?: { latitude: number; longitude: number; description?: string; address?: string; url?: string };
  /** Present on `order` messages only: the placed cart, plus the single-order token for its items. */
  order?: { orderId: string; token?: string };
  /** Present on `product` messages only: the catalog product shared into the chat. */
  product?: { productId: string; title?: string; description?: string; businessOwnerJid?: Jid };
}

/** Paginated payload returned by `GET /sessions/:id/messages`. */
export interface MessageListResponse {
  /** Unknown message-time rows in the selected scope; present for time selections only. */
  unknownTimestampTotal?: number;
  messages: MessageRecord[];
  total: number;
}

export interface ReactionSender {
  senderId: Jid;
  emoji: string;
  /** Unix timestamp in seconds. */
  timestamp: number;
}

/** One emoji and everyone who reacted with it (server returns `MessageReaction[]`). */
export interface ReactionRecord {
  emoji: string;
  senders: ReactionSender[];
}

// ── Bulk ──────────────────────────────────────────────────────────

export type BulkMessageType = 'text' | 'image' | 'video' | 'audio' | 'document';

export interface BulkMessageContent {
  text?: string;
  image?: BulkMediaRequest;
  video?: BulkMediaRequest;
  audio?: BulkMediaRequest;
  document?: BulkMediaRequest;
  caption?: string;
  /** WIDs to @mention (e.g. `["[email protected]"]`). The text/caption must also contain the `@<number>` token. */
  mentions?: string[];
}

export interface BulkMessageItem {
  chatId: Jid;
  type: BulkMessageType;
  content: BulkMessageContent;
  variables?: Record<string, string>;
}

export interface SendBulkRequest {
  messages: BulkMessageItem[];
  /** Optional caller-supplied idempotency/batch id. */
  batchId?: string;
  options?: {
    /** Minimum 1000 ms; default 3000. */
    delayBetweenMessages?: number;
    /** Randomize the delay between messages to look less automated. */
    randomizeDelay?: boolean;
    stopOnError?: boolean;
  };
}

export interface BulkMessageResponse {
  batchId: string;
  status: string;
  totalMessages: number;
  estimatedCompletionTime?: string;
  statusUrl: string;
}

/** Progress counters for a bulk-send batch. */
export interface BatchProgress {
  total: number;
  sent: number;
  failed: number;
  pending: number;
  cancelled: number;
}

/** Per-message outcome within a batch result list. */
export interface BatchMessageResult {
  chatId: Jid;
  status: BatchMessageStatus;
  messageId?: string;
  sentAt?: string;
  error?: { code: string; message: string };
}

/** Lifecycle of one recipient's send inside a batch — the `status` of {@link BatchMessageResult}. */
export type BatchMessageStatus = 'pending' | 'sent' | 'failed' | 'cancelled';

/**
 * Response from `GET /messages/batch/:batchId` (batch status polling). Distinct from
 * {@link BulkMessageResponse} (the send-bulk acknowledgement) and {@link BatchCancelResponse}.
 */
export interface BatchStatusResponse {
  batchId: string;
  status: BatchLifecycleStatus;
  progress: BatchProgress;
  results: BatchMessageResult[];
  startedAt?: string | null;
  completedAt?: string | null;
}

/** Response from `POST /messages/batch/:batchId/cancel`: the batch state without per-recipient `results`. */
export interface BatchCancelResponse {
  batchId: string;
  status: BatchLifecycleStatus;
  progress: BatchProgress;
}

/** Lifecycle of a whole batch — the `status` of {@link BatchStatusResponse}. */
export type BatchLifecycleStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'cancelled';

// ── Contact ───────────────────────────────────────────────────────

export interface ContactRecord {
  id: Jid;
  /** The name from the account's own addressbook. Absent for a contact that was never saved. */
  name?: string;
  /** MSISDN digits, without a leading + or any separators. */
  number: string;
  /** The name the contact set on their own account. Both engines emit this as `pushName`. */
  pushName?: string;
  /** Whether the entry exists in the account's addressbook. */
  isMyContact: boolean;
  /**
   * Whether the account has blocked this contact. Reflects the account's real blocklist on both
   * engines. When the blocklist query fails the field stays at its default rather than reporting
   * "nobody is blocked", and the gateway logs a warning — so a `false` is not proof the contact is
   * unblocked if the link is unhealthy.
   */
  isBlocked: boolean;
  /**
   * A cached picture URL. Only Baileys can fill it (whatsapp-web.js never sets it) and it is often
   * absent there too, so its absence does not say whether the contact has a picture.
   */
  profilePicUrl?: string;
}

export interface CheckNumberResponse {
  number: string;
  exists: boolean;
  /**
   * The chat id WhatsApp holds for the number, in the neutral `<phone>@c.us` form on both engines (it can
   * differ from the digits supplied), or `null` when the number is not registered.
   */
  whatsappId: string | null;
}

export interface ProfilePictureResponse {
  url: string | null;
}

/** Batch profile-picture lookup: a map of contact id → picture URL (null when the lookup failed). An id skipped after a lookup timed out is absent from the map; ask for it again. */
export interface ProfilePicturesResponse {
  pictures: Record<string, string | null>;
}

export interface ContactPhoneResponse {
  contactId: Jid;
  phone: string | null;
}

// ── Group ─────────────────────────────────────────────────────────

export interface GroupParticipant {
  id: Jid;
  number: string;
  name?: string;
  isAdmin: boolean;
  isSuperAdmin: boolean;
}

/** Item returned by `GET /sessions/:id/groups` (the slim list shape), and the `groups.create` response. */
export interface GroupSummary {
  id: Jid;
  name: string;
  /** Only in a `groups.create` response, never in `groups.list`; `groups.get` carries the participants. */
  participantsCount?: number;
  /** Only in a `groups.create` response, never in `groups.list`; `groups.get` carries each participant's role. */
  isAdmin?: boolean;
  /** JID of the parent community, or null if standalone. */
  linkedParentJID?: string | null;
}

/** Full detail returned by `GET /sessions/:id/groups/:groupId`. */
export interface GroupInfo {
  id: Jid;
  name: string;
  description?: string;
  /** Only admins may send messages. */
  announce?: boolean;
  /** Disappearing-messages timer in seconds; 0 or absent means off. */
  ephemeralSeconds?: number;
  /** Only admins may edit subject, description and picture. */
  locked?: boolean;
  /** Who may add participants. Absent when the engine did not report it. */
  memberAddMode?: 'all' | 'admins';
  owner?: Jid | null;
  /** Unix timestamp in seconds. */
  createdAt?: number;
  participants: GroupParticipant[];
  isReadOnly?: boolean;
  isAnnounce?: boolean;
  linkedParentJID?: string | null;
}

/** How a pending join request was made, when the engine reports it. */
export type GroupMembershipRequestMethod = 'invite_link' | 'non_admin_add' | 'linked_group_join';

/** A pending request to join a group. Only `participantId` is always present. */
export interface GroupMembershipRequest {
  /** Neutral id of the user asking to join. */
  participantId: Jid;
  /** Who created the request — differs from the requester on a non-admin add. */
  addedById?: Jid;
  method?: GroupMembershipRequestMethod;
  /** Unix seconds the request was created. */
  requestedAt?: number;
}

export interface CreateGroupRequest {
  name: string;
  participants: Jid[];
}

export interface ParticipantsRequest {
  participants: Jid[];
}

export interface GroupSubjectRequest {
  subject: string;
}

export interface GroupDescriptionRequest {
  /** May be empty to clear. */
  description: string;
}

export interface GroupMemberLabelRequest {
  /** At most 30 UTF-16 code units (an astral emoji counts as two). May be empty to clear. */
  label: string;
}

export interface InviteCodeResponse {
  inviteCode: string;
  inviteLink: string;
  message?: string;
}

export interface JoinGroupRequest {
  /** Group invite code (the token from a `https://chat.whatsapp.com/<code>` link); max 128 chars. */
  inviteCode: string;
}

export interface JoinGroupResponse {
  success: boolean;
  groupId: Jid;
}

/** Who may add participants to a group. */
export type GroupMemberAddMode = 'all' | 'admins';

/** Group settings as returned by `GET /sessions/:id/groups/:groupId/settings`. */
export interface GroupSettingsResponse {
  /** Only admins can send messages (announce group). */
  announce?: boolean;
  /** Only admins can edit group info (locked group). */
  locked?: boolean;
  /** Disappearing-messages timer in seconds; 0 disables. Known values: 86400 (24h), 604800 (7d), 7776000 (90d). */
  ephemeralSeconds?: number;
  /** Who may add participants: 'all' (any member) or 'admins' (admins only). */
  memberAddMode?: GroupMemberAddMode;
}

/**
 * Body for `PUT /sessions/:id/groups/:groupId/settings`. At least one field must be
 * present (the server answers 400 on an empty body); `ephemeralSeconds` is rejected
 * with 501 on the whatsapp-web.js engine.
 */
export type UpdateGroupSettingsRequest = GroupSettingsResponse;

// ── Profile (the session's own account) ───────────────────────────

export interface SetProfileNameRequest {
  /** New display name (WhatsApp limit: 25 characters). */
  name: string;
}

export interface SetProfileStatusRequest {
  /** New about/status text (may be empty to clear it; WhatsApp limit: 139 characters). */
  status: string;
}

/** Provide `url` OR `base64` (with `mimetype`). Mirrors the media acceptance pattern of sends. */
export interface SetProfilePictureRequest {
  /** Image URL (http/https); mutually exclusive with `base64`. */
  url?: string;
  /** Base64 encoded image data; requires `mimetype`. */
  base64?: string;
  /** Image MIME type (required when using `base64`). */
  mimetype?: string;
}

// ── Webhook ───────────────────────────────────────────────────────

/** Events a webhook may subscribe to. Use `*` to receive all except `message.receipt`, which must be named. */
export type WebhookEvent =
  | 'message.received'
  | 'message.sent'
  | 'message.ack'
  | 'message.receipt'
  | 'message.failed'
  | 'message.revoked'
  | 'message.reaction'
  | 'message.edited'
  | 'session.status'
  | 'session.qr'
  | 'session.authenticated'
  | 'session.disconnected'
  | 'session.reconnect_loop'
  | 'session.restriction'
  | 'presence.update'
  | 'event.response'
  | 'poll.vote'
  | 'call.accepted'
  | 'call.rejected'
  | 'call.missed'
  | 'group.join'
  | 'group.leave'
  | 'group.update'
  | 'group.join_request'
  | 'call.received'
  | 'status.received'
  | '*';

/**
 * The JSON body of a webhook delivery (docs/06 section 6.6). `event` is `'test'` for a delivery
 * sent by the test endpoint. Verify the raw body with `verifyWebhookSignature` before parsing it.
 */
export interface WebhookDelivery<TData = Record<string, unknown>> {
  event: Exclude<WebhookEvent, '*'> | 'test';
  timestamp: string;
  sessionId: string;
  idempotencyKey: string;
  deliveryId: string;
  data: TData;
}

export interface WebhookFilterCondition {
  field: string;
  operator: 'contains' | 'equals' | 'is' | 'isNot';
  /**
   * Polymorphic per field kind: a single string (text fields), a string array
   * (id/idArray/enum fields), or a boolean (boolean fields).
   */
  value: string | string[] | boolean;
  /** Only meaningful for text fields (`contains`/`equals`). Defaults to false. */
  caseSensitive?: boolean;
}

export interface WebhookFilters {
  conditions: WebhookFilterCondition[];
}

export interface CreateWebhookRequest {
  url: string;
  events?: WebhookEvent[];
  /**
   * HMAC secret; signed as `X-OpenWA-Signature: sha256=…`. At least 16 characters, or the gateway
   * answers 400. Omit for unsigned deliveries. Never returned by a read.
   */
  secret?: string;
  headers?: Record<string, string>;
  filters?: WebhookFilters | null;
  /**
   * Total delivery attempts per event including the first, 0 to 5 (0 and 1 both mean one attempt); default 3 on
   * create, while an update that omits it keeps the current value. Server DTO field is `retryCount`.
   */
  retryCount?: number;
}

/**
 * Every field is a partial update. `secret: ''` and `headers: {}` are the documented "clear it"
 * values; any other secret is still held to the 16-character minimum.
 */
export type UpdateWebhookRequest = Partial<CreateWebhookRequest> & { active?: boolean };

export interface WebhookResponse {
  id: string;
  sessionId: string;
  url: string;
  events: WebhookEvent[];
  active: boolean;
  filters?: WebhookFilters | null;
  retryCount: number;
  /** ISO timestamp of the last delivery attempt, or null if never triggered. */
  lastTriggeredAt?: string | null;
  createdAt: string;
  updatedAt: string;
  // NOTE: the server deliberately omits `secret` and `headers` from read responses.
}

export interface WebhookTestResult {
  success: boolean;
  statusCode?: number;
  error?: string;
}

/** A webhook delivery the gateway gave up on or could not dispatch, as listed by the delivery-failure log. */
export interface WebhookDeliveryFailure {
  id: string;
  webhookId: string;
  sessionId: string;
  event: string;
  url: string;
  /** The idempotency key the receiver would have deduped on. */
  idempotencyKey?: string | null;
  deliveryId?: string | null;
  /** Attempts made before giving up; 0 when the delivery was not given up after retries (see `deliveryFailures`). */
  attempts: number;
  /** Last HTTP status when the failure was a non-2xx response; null for a network or timeout error. */
  lastStatusCode?: number | null;
  lastError: string;
  /** ISO timestamp of when the row was recorded. */
  createdAt: string;
  /**
   * True when the row still holds the event data and can be replayed with
   * {@link WebhooksResource.redriveDeliveryFailures}: a terminal row (`attempts > 0`) recorded while the
   * gateway's `WEBHOOK_FAILURE_PAYLOAD_RETENTION_HOURS` is above 0, until that window passes.
   */
  replayable: boolean;
}

/** Body of {@link WebhooksResource.redriveDeliveryFailures}. An empty body takes the least-retried eligible rows. */
export interface RedriveWebhookDeliveriesRequest {
  /** Only rows of this session (within the key's allowedSessions). */
  sessionId?: string;
  /** Only rows of this webhook. */
  webhookId?: string;
  /** Only these failure rows (ids from `deliveryFailures`), at most 500. */
  ids?: string[];
  /** Max rows replayed by this call (1-500, default 100). */
  limit?: number;
}

/** Outcome of {@link WebhooksResource.redriveDeliveryFailures}. */
export interface WebhookRedriveResult {
  /** Rows replayed by this call: delivered plus enqueued. */
  redriven: number;
  /** Delivered by a direct POST; their failure rows were removed. */
  delivered: number;
  /** Reserved for compatibility; operator redrive always returns zero. */
  enqueued: number;
  /** Replays that failed again; their rows stay, with attempts raised by one. */
  failed: number;
  /** Rows not replayed: the webhook was removed, disabled or unsubscribed, or a plugin cancelled it. */
  skipped: number;
  /** Replayable rows still in scope after this call. */
  remaining: number;
}

// ── Chat (session-scoped chat operations) ─────────────────────────

export interface ChatSummary {
  id: Jid;
  name: string;
  isGroup: boolean;
  unreadCount: number;
  /** Preview text of the last message (the server returns a plain string, not an object). */
  lastMessage?: string;
  lastMessageType?: MessageType;
  /** Unix seconds of the last activity. */
  timestamp: number;
  kind: ChatKind;
  /** Archived state, as set via {@link ChatsResource.archive}. */
  archived: boolean;
  /** Pinned state, as set via {@link ChatsResource.pin}. */
  pinned: boolean;
  /** Whether the chat is muted right now, as set via {@link ChatsResource.mute}. */
  muted: boolean;
  /** Epoch milliseconds the mute ends, present only when muted; 0 means indefinitely. */
  muteExpiration?: number;
}

/** Body for {@link SessionsResource.setOnlinePresence}. */
export interface SetOwnPresenceRequest {
  /** `true` = appear online; `false` = appear offline, handing notifications back to the phone. */
  available: boolean;
}

/** Which kind of call a link opens. WhatsApp's own URL path for `audio` is `/voice/`. */
export type CallLinkType = 'audio' | 'video';

/** Body for {@link CallsResource.createLink}. */
export interface CreateCallLinkRequest {
  type: CallLinkType;
  /** Absolute epoch MILLISECONDS the call is scheduled to start at. */
  startTime: number;
}

/** Result of {@link CallsResource.createLink}. */
export interface CallLinkResponse {
  /** The shareable WhatsApp call link. */
  link: string;
}

/** Body for {@link ChannelsResource.demoteAdmin}. */
export interface DemoteChannelAdminRequest {
  /** WhatsApp ID of the admin to demote back to a subscriber. */
  userId: Jid;
}

/** Body for {@link ChannelsResource.transferOwnership}. */
export interface TransferChannelOwnershipRequest {
  /** WhatsApp ID of the account that becomes the new owner. */
  newOwnerId: Jid;
}

/** Body for {@link ChatsResource.markUnread}. */
export interface MarkChatRequest {
  chatId: Jid;
}

/** Body for {@link ChatsResource.subscribePresence}. */
export interface SubscribePresenceRequest {
  chatId: Jid;
}

/** Body for {@link ChatsResource.markRead}. */
export interface MarkChatReadRequest extends MarkChatRequest {
  /**
   * Specific message IDs to acknowledge. Baileys acknowledges individual messages, so without this
   * only the newest received message gets a receipt (the one the engine holds in memory, else the
   * newest received one the gateway stored): a burst leaves its earlier messages unread forever.
   * Callers that persist inbound message IDs should send them here. Ignored by whatsapp-web.js,
   * whose own sendSeen is chat-level. At most 100 per request; an empty array is rejected.
   */
  messageIds?: string[];
}

export type ChatState = 'typing' | 'recording' | 'paused';

export interface SendChatStateRequest {
  chatId: Jid;
  state: ChatState;
}

export interface DeleteChatRequest {
  chatId: Jid;
}

// ── Status / Stories ──────────────────────────────────────────────

/**
 * One status/story from the GET status endpoints (`list`/`fromContact`), which answer a
 * `{ statuses: [...] }` envelope. Mirrors the backend `Status` — the engine payload is returned
 * as-is, with no DTO in between.
 */
export interface StatusRecord {
  id: string;
  /** Whose story this is. */
  contact: {
    id: Jid;
    name?: string;
    pushName?: string;
  };
  type: 'text' | 'image' | 'video' | 'voice';
  /** Text body for a text status, caption for an image/video one. */
  caption?: string;
  mediaUrl?: string;
  backgroundColor?: string;
  font?: number;
  /** ISO 8601 timestamp of the post. */
  timestamp: string;
  /** ISO 8601 expiry — 24h after `timestamp`. */
  expiresAt: string;
}

/**
 * Result of a status POST (`send-text`/`send-image`/`send-video`/`send-voice`).
 * Mirrors the backend `StatusResult` exactly.
 */
export interface StatusResult {
  statusId: string;
  /** ISO 8601 timestamp of the post. */
  timestamp: string;
  /** ISO 8601 expiry timestamp. */
  expiresAt: string;
}

export interface SendTextStatusRequest {
  text: string;
  /** Recipient JIDs. Required on the Baileys engine (absent/empty → 400); omit on whatsapp-web.js, which broadcasts instead. */
  recipients?: string[];
  /** Hex background color, e.g. `#25D366`. */
  backgroundColor?: string;
  /**
   * WhatsApp status font family: 0 (default), 1, 2, 6 (bold), 7, 8, 9, 10. whatsapp-web.js honors only
   * 0 to 7 and posts 8, 9 and 10 in the default font.
   */
  font?: 0 | 1 | 2 | 6 | 7 | 8 | 9 | 10;
}

/** Media payload for a status post: provide `url` OR `base64`. */
export interface StatusMediaInput {
  url?: string;
  base64?: string;
  /**
   * MIME type of the media. When omitted the server uses the route's default (`image/jpeg`, `video/mp4` or
   * `audio/ogg; codecs=opus`), which also overrides a URL's Content-Type; the bytes are never inspected. Set
   * it for base64 and for any media of another type.
   */
  mimetype?: string;
}

/** Server expects a nested `{ image: { url|base64 } }` body, not flat media fields. */
export interface SendImageStatusRequest {
  image: StatusMediaInput;
  /** Recipient JIDs. Required on the Baileys engine (absent/empty → 400); omit on whatsapp-web.js, which broadcasts instead. */
  recipients?: string[];
  caption?: string;
}

/** Server expects a nested `{ video: { url|base64 } }` body, not flat media fields. */
export interface SendVideoStatusRequest {
  video: StatusMediaInput;
  /** Recipient JIDs. Required on the Baileys engine (absent/empty → 400); omit on whatsapp-web.js, which broadcasts instead. */
  recipients?: string[];
  caption?: string;
}

/**
 * A voice status carries no caption — WhatsApp has nowhere to render one on a status voice note.
 *
 * `audio.mimetype` defaults to `audio/ogg; codecs=opus`, which is the only format WhatsApp plays as a
 * status voice note. Neither engine transcodes, so produce those bytes with `media.convertVoice`.
 */
export interface SendVoiceStatusRequest {
  audio: StatusMediaInput;
  /** Recipient JIDs. Required on the Baileys engine (absent/empty → 400); omit on whatsapp-web.js, which broadcasts instead. */
  recipients?: string[];
  /** Background colour as `#RRGGBB`, rendered behind the voice-note bubble. Baileys only; whatsapp-web.js ignores it. */
  backgroundColor?: string;
}

// ── Health ────────────────────────────────────────────────────────

export interface HealthResponse {
  status: string;
  timestamp: string;
  version?: string;
}

export interface HealthDependencyStatus {
  status: 'up' | 'down';
}

export interface HealthReadyDetails {
  mainDatabase?: HealthDependencyStatus;
  dataDatabase?: HealthDependencyStatus;
}

export interface HealthReadyResponse {
  status: string;
  details: HealthReadyDetails;
}

// ── Auth ──────────────────────────────────────────────────────────

export interface AuthValidateResponse {
  valid: boolean;
  /** The key's role; present only when the key is valid. */
  role?: 'admin' | 'operator' | 'viewer';
  engineType?: string;
  scoped?: boolean;
}

// ── Template ──────────────────────────────────────────────────────

export interface TemplateRecord {
  id: string;
  sessionId: string;
  name: string;
  /** Template body with `{{variable}}` placeholders. */
  body: string;
  header?: string | null;
  footer?: string | null;
  createdAt: string;
  updatedAt: string;
}

export interface CreateTemplateRequest {
  /** Unique template name within the session. */
  name: string;
  body: string;
  header?: string;
  footer?: string;
}

export type UpdateTemplateRequest = Partial<CreateTemplateRequest>;

// ── Label (WhatsApp Business) ─────────────────────────────────────

/** Mirrors the backend `Label` — returned by the engine as-is, with no DTO in between. */
export interface LabelRecord {
  id: string;
  name: string;
  /** Label colour as a hex string, e.g. `#25D366`. */
  hexColor: string;
}

export interface AddLabelRequest {
  labelId: string;
}

// ── Channel / Newsletter ──────────────────────────────────────────

/** Mirrors the backend `Channel` — returned by the engine as-is, with no DTO in between. */
export interface ChannelRecord {
  id: Jid;
  name: string;
  description?: string;
  /** Invite code from the channel link. */
  inviteCode?: string;
  subscriberCount?: number;
  /** Channel picture URL. Not currently filled by either engine. */
  picture?: string;
  verified?: boolean;
  /** Channel creation time as reported by the engine. Populated by Baileys; whatsapp-web.js omits it. */
  createdAt?: number;
}

/**
 * A message read live from a channel by `channels.messages()`. This is the engine payload
 * (backend `ChannelMessage`), NOT the persisted {@link MessageRecord} — that endpoint reads
 * WhatsApp directly and never touches the message store.
 */
export interface ChannelMessageRecord {
  id: string;
  body: string;
  /** Unix timestamp in seconds. */
  timestamp: number;
  hasMedia: boolean;
  mediaUrl?: string;
}

export interface ChannelMessageQuery {
  /** Max messages to return (default 50, max 100: a larger value is cut to 100). */
  limit?: number;
}

export interface SubscribeChannelRequest {
  /** Channel invite code (from a channel link). */
  inviteCode: string;
}

// ── Catalog (Business) ────────────────────────────────────────────

export interface CatalogInfo {
  id: string;
  name: string;
  description?: string;
  /** Counts at most the first 51 products on Baileys. */
  productCount: number;
  url: string;
}

export interface CatalogProductsQuery {
  /** Page number (min 1, default 1). */
  page?: number;
  /** Page size (min 1, default 20). */
  limit?: number;
}

export interface CatalogProduct {
  id: string;
  name: string;
  description?: string;
  /** Absent when the product has no price. */
  price?: number;
  currency?: string;
  /** Absent when `price` is. */
  priceFormatted?: string;
  imageUrl?: string;
  url: string;
  isAvailable: boolean;
  retailerId?: string;
}

/** Paginated payload returned by `GET /sessions/:id/catalog/products`. */
export interface PaginatedProducts {
  products: CatalogProduct[];
  pagination: { page: number; limit: number; total: number; totalPages: number };
}

/**
 * Response of `send-product`. The route answers with the sent message's id under `id`, not the
 * `messageId` the other send routes use.
 */
export interface ProductMessageResponse {
  id: string;
  /** Unix SECONDS the engine stamped on the outgoing message. */
  timestamp: number;
}

export interface SendProductRequest {
  chatId: Jid;
  productId: string;
  /** Optional body/caption text. */
  body?: string;
}

// ── Search ────────────────────────────────────────────────────────

/**
 * How `q` matches: `word` (the server default) matches whole words; `contains` matches any part of a
 * word, ignoring case and accents, and needs at least one term of 3+ characters and a server with
 * `SEARCH_CONTAINS_ENABLED=true` (501 otherwise).
 */
export type SearchMatch = 'word' | 'contains';

/** Query parameters for `GET /search`. Only `q` is required; all filters are optional. */
export interface SearchParams {
  /**
   * Search term (required, non-empty — the server rejects empty/whitespace with 400). At most 1000
   * characters and 32 words, punctuation included; the server answers 400 above either.
   */
  q: string;
  /** Match mode; the server defaults to `word`. */
  match?: SearchMatch;
  /** Restrict to a single session. */
  sessionId?: string;
  /** Restrict to a single chat id. */
  chatId?: Jid;
  /** Restrict to incoming or outgoing messages. */
  direction?: MessageDirection;
  /** Message type filter (compared against stored `messages.type`). */
  type?: string;
  /** Sender filter. */
  from?: Jid;
  /** Epoch-ms lower bound (inclusive). */
  dateFrom?: number;
  /** Epoch-ms upper bound (inclusive). */
  dateTo?: number;
  /** Max hits to return (default 50; capped at the server's SEARCH_LIMIT_MAX, 100 by default). */
  limit?: number;
  /** Pagination offset (at most 100000; the server answers 400 above). */
  offset?: number;
}

/** A single search hit returned by `GET /search`. */
export interface SearchHit {
  messageId: string;
  waMessageId: string;
  sessionId: string;
  chatId: Jid;
  body: string;
  /** Provider-generated excerpt with `<mark>` highlight markers. Render as text, never as HTML. */
  snippet: string;
  /** Unix timestamp in seconds. */
  timestamp: number;
  type: string;
  direction: MessageDirection;
  from: Jid;
  /** Relevance score (provider-specific; may be absent). */
  score?: number;
}

/** Response from `GET /search`. */
export interface SearchResults {
  hits: SearchHit[];
  /** Bounded exact count for pagination. */
  total: number;
  tookMs: number;
  /** Which provider answered (id), e.g. `builtin-fts`. */
  provider: string;
}

/** Media to convert: exactly one of `url` or `base64`; `base64` wins if both are given. */
export interface ConvertMediaInput {
  /** Public http(s) URL the server fetches (SSRF-guarded). */
  url?: string;
  /** Inline bytes. No mimetype is needed — the input format is read from the bytes. */
  base64?: string;
}

/** The converted media, in the shape a send endpoint accepts. */
export interface ConvertedMedia {
  /** Converted bytes, ready to pass as a send endpoint's `base64`. */
  base64: string;
  /** What the bytes now are — not what they were. */
  mimetype: string;
  /** Decoded size, so a size check needs no decoding. */
  bytes: number;
}

/** Whether server-side conversion can actually be used on this deployment. */
export interface MediaConversionAvailability {
  available: boolean;
}