import { defineLogicFunction } from "twenty-sdk/define"; import { listConnections } from "twenty-sdk/logic-function"; import { SAJN_CONNECTION_PROVIDER_NAME, SAJN_ON_DISCONNECT_UNIVERSAL_IDENTIFIER, } from "src/constants/universal-identifiers"; import { clearSajnWebhookRegistration, configureSajnWebhook, } from "src/logic-functions/utils/sajn-webhook-registration"; type OnDisconnectPayload = { connectionProviderId: string; connectionProviderName: string; connectedAccountId: string; }; const handler = async (payload: OnDisconnectPayload): Promise => { if (payload.connectionProviderName !== SAJN_CONNECTION_PROVIDER_NAME) { return; } const remainingConnections = await listConnections({ providerName: SAJN_CONNECTION_PROVIDER_NAME, }); const replacement = remainingConnections.find((connection) => connection.visibility === "workspace") ?? remainingConnections[0]; if (replacement) { await configureSajnWebhook(replacement); return; } await clearSajnWebhookRegistration(); }; export default defineLogicFunction({ universalIdentifier: SAJN_ON_DISCONNECT_UNIVERSAL_IDENTIFIER, name: "cleanup-sajn-after-disconnect", description: "Stops accepting sajn webhooks when the last OAuth connection is removed.", timeoutSeconds: 30, handler, });