import { readBody } from "h3"; import { getAuthContext } from "../../../../../utils/auth"; import { prisma } from "../../../../../utils/prisma"; import { telegramBotApi } from "../../../../../utils/telegram"; type RefreshBody = { businessConnectionId?: string; }; function mapFlags(raw: any) { const isEnabled = typeof raw?.is_enabled === "boolean" ? raw.is_enabled : null; const canReply = typeof raw?.can_reply === "boolean" ? raw.can_reply : typeof raw?.rights?.can_reply === "boolean" ? raw.rights.can_reply : null; return { isEnabled, canReply }; } export default defineEventHandler(async (event) => { const auth = await getAuthContext(event); const body = await readBody(event); const businessConnectionId = String(body?.businessConnectionId ?? "").trim(); if (!businessConnectionId) { throw createError({ statusCode: 400, statusMessage: "businessConnectionId is required" }); } const existing = await prisma.telegramBusinessConnection.findFirst({ where: { teamId: auth.teamId, businessConnectionId, }, select: { id: true }, }); if (!existing) { throw createError({ statusCode: 404, statusMessage: "business connection not found" }); } const response = await telegramBotApi("getBusinessConnection", { business_connection_id: businessConnectionId }); const { isEnabled, canReply } = mapFlags(response); const updated = await prisma.telegramBusinessConnection.update({ where: { id: existing.id }, data: { isEnabled, canReply, rawJson: { state: "connected", refreshedAt: new Date().toISOString(), businessConnection: response, }, }, select: { businessConnectionId: true, isEnabled: true, canReply: true, updatedAt: true, }, }); return { ok: true, connection: { businessConnectionId: updated.businessConnectionId, isEnabled: updated.isEnabled, canReply: updated.canReply, updatedAt: updated.updatedAt.toISOString(), }, }; });