"use server"; // «Чаты» (PEP-62): a message into a chat/thread, Telegram group link/unlink. Access — chatForUser. import { chatForUser, createChatLinkCode, PeppaError, unlinkChat } from "@peppa/core"; import { postToChat } from "@peppa/runner"; import { loadEnv } from "@peppa/shared"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { asWebActor, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim(); /** Runs an action; errors come back as ?error=… (redirect stays outside try). */ async function attempt(f: FormData, fn: () => Promise): Promise { let target = str(f, "back") || "/chats"; try { target = (await fn()) || target; } catch (e) { const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`; const [path, query] = target.split("?"); const params = new URLSearchParams(query); params.set("error", msg.slice(0, 300)); target = `${path}?${params}`; } revalidatePath("/chats", "layout"); redirect(target); } export async function postChatAction(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { const thread = str(f, "thread"); await postToChat(db, user, { chatId: Number(str(f, "chatId")), threadKey: thread || null, text: String(f.get("text") ?? ""), via: "web" }); }); } /** A one-time code (10 min) for `/link <код>` in a group, or the startgroup link that sends it. */ export async function linkChatAction(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { const token = loadEnv().TELEGRAM_BOT_TOKEN; if (!token) throw new PeppaError("Telegram-бот Пеппы не настроен"); const chat = await chatForUser(db, user, Number(str(f, "chatId"))); const code = await createChatLinkCode(db, token, user, chat.id); const back = str(f, "back") || "/chats"; return `${back}${back.includes("?") ? "&" : "?"}link=${encodeURIComponent(code)}`; }); } export async function unlinkChatAction(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, () => unlinkChat(db, user, Number(str(f, "chatId")))); }