import { NextResponse } from "next/server"; import { promises as fs } from "fs"; import path from "path"; const MESSAGES_FILE = path.join(process.cwd(), ".messages.json"); type Msg = { id: string; from: string; text: string; ts: number; channel?: string }; async function getMessages(): Promise { try { const data = await fs.readFile(MESSAGES_FILE, "utf-8"); return JSON.parse(data) as Msg[]; } catch { return []; } } async function saveMessages(msgs: Msg[]) { const toSave = msgs.slice(-500); await fs.writeFile(MESSAGES_FILE, JSON.stringify(toSave, null, 2), "utf-8"); } export async function GET(req: Request) { const url = new URL(req.url); const channel = url.searchParams.get("channel") || "global"; const msgs = await getMessages(); const channelMsgs = msgs.filter((m) => m.channel === channel || channel === "all"); return NextResponse.json({ ok: true, messages: channelMsgs }); } export async function POST(req: Request) { try { const body = await req.json(); const { from, text, channel = "global" } = body; if (!from || !text) { return NextResponse.json({ ok: false, error: "Missing fields" }, { status: 400 }); } const newMsg: Msg = { id: Math.random().toString(36).slice(2, 10), from: from.trim(), text: text.trim().slice(0, 500), ts: Date.now(), channel, }; const msgs = await getMessages(); msgs.push(newMsg); await saveMessages(msgs); return NextResponse.json({ ok: true, message: newMsg }); } catch (err) { return NextResponse.json({ ok: false, error: "Failed to save message" }, { status: 500 }); } } export async function DELETE(req: Request) { try { const url = new URL(req.url); const id = url.searchParams.get("id"); const clearAll = url.searchParams.get("all") === "true"; let msgs = await getMessages(); if (clearAll) { msgs = []; } else if (id) { msgs = msgs.filter((m) => m.id !== id); } else { return NextResponse.json({ ok: false, error: "Provide id or all=true" }, { status: 400 }); } await saveMessages(msgs); return NextResponse.json({ ok: true }); } catch (err) { return NextResponse.json({ ok: false, error: "Failed to delete" }, { status: 500 }); } }