import * as z from "zod" import { defineAction } from "../../../automation/actions" import { findLabelIds, getGmailApi, } from "@automate.ax/integration-contracts/gmail" import { GMAIL_MODIFY_REQUIREMENT } from "../lib/scopes" import { LABELS_SCHEMA, MESSAGE_IDS_SCHEMA, } from "@automate.ax/integration-contracts/gmail" /** * Adds and removes multiple Gmail labels in one batch request. * * Label display names and immutable IDs may be mixed in either list. */ export const modifyGmailLabels = defineAction("Modify Gmail labels") .describe("Adds and removes Gmail labels in one batch request.") .account("google", GMAIL_MODIFY_REQUIREMENT) .input( z .object({ /** Label names or IDs to add. */ add: LABELS_SCHEMA.optional(), /** One ID or up to 1,000 immutable Gmail message IDs. */ messageIds: MESSAGE_IDS_SCHEMA, /** Label names or IDs to remove. */ remove: LABELS_SCHEMA.optional(), }) .refine( (input) => Boolean(input.add?.length || input.remove?.length), "At least one label must be added or removed.", ), ) .output(z.string().array()) .retry({ replaySafety: "unsafe" }) .handler(async ({ account, input }) => { const gmailApi = getGmailApi(account.secret) const labelIds = await findLabelIds(gmailApi, [ ...(input.add ?? []), ...(input.remove ?? []), ]) const { messageIds } = input await gmailApi.users.messages.batchModify({ requestBody: { addLabelIds: labelIds.slice(0, input.add?.length ?? 0), ids: messageIds, removeLabelIds: labelIds.slice(input.add?.length ?? 0), }, userId: "me", }) return messageIds })