import { and, eq } from "drizzle-orm"; import { after } from "next/server"; import { getDb } from "@/db"; import { commissionMessages, commissionTickets } from "@/db/schema"; import type { CommissionMessageEvent } from "@/lib/commission/message-event"; import { sendCommissionMessagePush } from "@/lib/commission/push"; import { notifyCommission } from "@/lib/commission/server"; import { authorizeTicket } from "@/lib/commission/tickets"; import { getMediaStorage } from "@/lib/media/storage"; import { inspectImage } from "@/lib/media/inspect"; import { boundedBody, errorResponse, HttpError, requireSameOrigin, withUploadSlot } from "@/lib/security/http"; import { limitRequest } from "@/lib/security/rate-limit"; import * as z from "zod"; export async function POST(request: Request, context: RouteContext<"/api/commission/tickets/[id]/messages">) { try { requireSameOrigin(request); const { id } = await context.params; const { ticket, user } = await authorizeTicket(id); if (ticket.status !== "open") throw new HttpError(409, "ticket-closed"); await limitRequest("commission-message", user.id, 60); if (!request.headers.get("content-type")?.startsWith("multipart/form-data;")) throw new HttpError(415, "expected-multipart"); return await withUploadSlot(async () => { const form = await boundedBody(request, 6 * 1024 * 1024 + 64 * 1024).formData(); const value = form.get("text"); const body = typeof value === "string" ? value.trim() : ""; const image = form.get("image"); const replyValue = form.get("replyToId"); const replyToId = replyValue === null || replyValue === "" ? null : replyValue; if (body.length > 4000 || (image && !(image instanceof File))) throw new HttpError(400, "invalid-message"); if (replyToId !== null) { if (typeof replyToId !== "string" || !z.uuid().safeParse(replyToId).success) throw new HttpError(400, "invalid-reply"); const [parent] = await getDb().select({ id: commissionMessages.id }).from(commissionMessages) .where(and(eq(commissionMessages.id, replyToId), eq(commissionMessages.ticketId, id))).limit(1); if (!parent) throw new HttpError(404, "reply-not-found"); } if (!body && !image) throw new HttpError(400, "empty-message"); let imageObjectKey: string | null = null; if (image instanceof File) { if (image.size === 0 || image.size > 6 * 1024 * 1024 || !["image/png", "image/jpeg", "image/webp"].includes(image.type)) throw new HttpError(415, "invalid-message-image"); const bytes = new Uint8Array(await image.arrayBuffer()); await inspectImage(bytes, image.type as "image/png" | "image/jpeg" | "image/webp"); imageObjectKey = `commission/messages/${crypto.randomUUID()}`; await (await getMediaStorage()).write(imageObjectKey, bytes, { type: image.type, acl: "public-read" }); } let messageId: string; try { messageId = await getDb().transaction(async (tx) => { const [message] = await tx.insert(commissionMessages).values({ ticketId: id, authorId: user.id, replyToId, text: body || null, imageObjectKey, imageMimeType: image instanceof File ? image.type : null }) .returning({ id: commissionMessages.id }); await tx.update(commissionTickets).set({ updatedAt: new Date() }).where(eq(commissionTickets.id, id)); return message.id; }); } catch (cause) { if (imageObjectKey) await (await getMediaStorage()).delete(imageObjectKey).catch(() => undefined); throw cause; } const message: CommissionMessageEvent = { messageId, ticketId: id, ticketTitle: ticket.title || `Ticket #${id.slice(0, 8)}`, authorId: user.id, authorName: user.name, text: body || null }; await notifyCommission(id, ticket.userId, `message:${JSON.stringify(message)}`); after(() => sendCommissionMessagePush({ id: messageId, ticketId: id, ticketTitle: message.ticketTitle, customerId: ticket.userId, authorId: user.id, authorName: user.name, text: body || null }).catch(() => { console.error("Commission push delivery failed"); })); return Response.json({ ok: true, messageId }, { status: 201 }); }); } catch (cause) { return errorResponse(cause); } }