import { rm } from "node:fs/promises"; import { join } from "node:path"; import { db } from "../db.js"; import { env } from "../env.js"; import { sessionManager } from "../whatsapp/session-manager.js"; import { writeAuditLog } from "../audit.js"; import { pgNotifyWeb } from "./notify.js"; import { logger } from "../logger.js"; /** * Unpair handler: stop the live Baileys session and remove session files. * The web's unpair action deletes the account row before notifying us, * so we expect the row to be gone by the time we run. Audit log uses a * null operator since the row is no longer queryable. */ export async function handleUnpair(accountId: string): Promise { await sessionManager.stop(accountId); await rm(join(env.SESSIONS_DIR, accountId), { recursive: true, force: true }); try { await writeAuditLog(db, { operatorId: null, source: "web", action: "account.unpaired", targetType: "whatsapp_account", targetId: accountId, payload: {}, }); } catch (err) { logger.warn({ err, accountId }, "unpair: audit log failed (non-fatal)"); } await pgNotifyWeb({ type: "session.disconnected", accountId }); }