// routes/api/create/message.ts import { define } from "../../../utils.ts"; import { createMessage } from "../../../services/messageService.ts"; import { SessionCookie } from "../../auth/callback.ts"; export const handler = define.handlers({ async POST(ctx) { try { const stateData: SessionCookie = ctx.state.data; const { user_id } = stateData; 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 = { lease_id: formData.get("lease_id")?.toString() || "", recipient_id: formData.get("recipient_id")?.toString() || "", message_type: formData.get("message_type")?.toString() || "", subject: formData.get("subject")?.toString() || "", content: formData.get("content")?.toString() || "", }; } const lease_id = data.lease_id || null; const recipient_id = data.recipient_id; const message_type = data.message_type; const subject = data.subject; const content = data.content; if (!recipient_id || !message_type || !subject || !content) { return new Response( JSON.stringify({ error: "Recipient ID, message type, subject, and encrypted content are required", }), { status: 400, headers: { "Content-Type": "application/json" }, }, ); } const [created] = await createMessage( lease_id, user_id, // sender_id recipient_id, message_type, subject, content, ); // Return appropriate response based on request type if (isJsonRequest) { return new Response( JSON.stringify({ success: true, message: created ?? null, }), { 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" }, }); } }, });