// routes/api/update/message.ts import { define } from "../../../utils.ts"; import { markAllMessagesAsRead, markMessageAsReadForUser, } from "../../../services/messageService.ts"; import { SessionCookie } from "../../auth/callback.ts"; export const handler = define.handlers({ async POST(ctx) { try { const stateData: SessionCookie | null = ctx.state.data ?? null; const user_id = stateData?.user_id; if (!user_id) { return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401, headers: { "Content-Type": "application/json" }, }); } const contentType = ctx.req.headers.get("content-type") || ""; let data: Record = {}; let sender: string | null = null; let isJsonRequest = false; // Handle both JSON and form data if (contentType.includes("application/json")) { isJsonRequest = true; const jsonData = await ctx.req.json(); data = jsonData; } else { const formData = await ctx.req.formData(); sender = formData.get("sender")?.toString() || null; data = { id: formData.get("id")?.toString() || "", mark_all_read: formData.get("mark_all_read") === "true", }; } const id = data.id as string; const mark_all_read = data.mark_all_read as boolean; let result; if (mark_all_read) { // Mark all messages as read for the user result = await markAllMessagesAsRead(user_id); } else if (id) { // Mark specific message as read result = await markMessageAsReadForUser(id, user_id); } else { return new Response( JSON.stringify({ error: "Either message ID or mark_all_read flag is required", }), { status: 400, headers: { "Content-Type": "application/json" }, }, ); } // Return appropriate response based on request type if (isJsonRequest) { return new Response( JSON.stringify({ success: true, updated_count: result.length, }), { status: 200, headers: { "Content-Type": "application/json" }, }, ); } else { // Redirect back to the sender URL const senderPath = sender?.toString() || "/"; let redirectUrl = senderPath; try { if (senderPath.startsWith("/")) { const url = new URL(ctx.req.url); redirectUrl = url.origin + senderPath; } } catch (_) { // fallback: just use senderPath } return Response.redirect(redirectUrl, 303); } } catch (e) { return new Response(JSON.stringify({ error: e }), { status: 500, headers: { "Content-Type": "application/json" }, }); } }, });