import { eq, inArray } from "drizzle-orm"; import type { createDb } from "@/db"; import { comments, notifications, profiles } from "@/db/schema"; import { extractMentions } from "@/lib/sanitize"; type Db = ReturnType; export async function createCommentNotifications( db: Db, opts: { commentId: string; eventId: string; actorId: string; parentId: string | null; body: string; }, ) { const notifs: Array<{ profileId: string; type: "reply" | "mention"; actorId: string; commentId: string; eventId: string; }> = []; if (opts.parentId) { const [parent] = await db .select({ profileId: comments.profileId }) .from(comments) .where(eq(comments.id, opts.parentId)); if (parent && parent.profileId !== opts.actorId) { notifs.push({ profileId: parent.profileId, type: "reply", actorId: opts.actorId, commentId: opts.commentId, eventId: opts.eventId, }); } } const mentions = extractMentions(opts.body); if (mentions.length > 0) { const mentioned = await db .select({ id: profiles.id, username: profiles.username }) .from(profiles) .where(inArray(profiles.username, mentions)); for (const p of mentioned) { if (p.id !== opts.actorId && !notifs.some((n) => n.profileId === p.id)) { notifs.push({ profileId: p.id, type: "mention", actorId: opts.actorId, commentId: opts.commentId, eventId: opts.eventId, }); } } } if (notifs.length > 0) { await db.insert(notifications).values(notifs); } }