import path from 'path'; import fs from 'fs'; import { decrypt } from '../utils/crypto'; import * as repo from '../repositories/supportRepository'; import { SupportConversationRow, SupportMessageRow, SupportSenderType, } from '../models/support.model'; import { getTypingIndicators, publishSupportEvent, setTypingIndicator, } from './supportRealtimeService'; const STAFF_ROLES = new Set(['admin', 'moderator', 'super_admin']); export function isStaffRole(role: string | undefined): boolean { return !!role && STAFF_ROLES.has(role); } function previewForMessage(body: string | null, attachmentName: string | null): string { if (body?.trim()) return body.trim().slice(0, 200); if (attachmentName) return `📎 ${attachmentName}`; return 'Message'; } function mapMessage(row: SupportMessageRow, staffNames?: Map) { const staffName = row.sender_type === 'staff' && row.sender_user_id ? staffNames?.get(row.sender_user_id) ?? null : null; return { id: row.id, conversationId: row.conversation_id, senderType: row.sender_type, senderUserId: row.sender_user_id, senderDisplayName: staffName, body: row.body, attachmentUrl: row.attachment_url, attachmentName: row.attachment_name, attachmentMime: row.attachment_mime, readAt: row.read_at?.toISOString() ?? null, createdAt: row.created_at.toISOString(), }; } function mapConversation(row: SupportConversationRow) { return { id: row.id, userId: row.user_id, visitorToken: row.visitor_token, isAnonymous: row.user_id == null, subject: row.subject, status: row.status, assignedTo: row.assigned_to, lastMessageAt: row.last_message_at?.toISOString() ?? null, lastMessagePreview: row.last_message_preview, unreadUser: row.unread_user, unreadStaff: row.unread_staff, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString(), }; } function decryptEmail(encrypted: string | null): string | null { if (!encrypted) return null; try { return decrypt(encrypted); } catch { return null; } } export type SupportAccessContext = { userId?: string; role?: string; visitorToken?: string | null; }; export async function assertConversationAccess( conversationId: string, ctx: SupportAccessContext ): Promise { const conv = await repo.findConversationById(conversationId); if (!conv) throw new Error('Conversation not found'); if (isStaffRole(ctx.role)) return conv; if (ctx.userId && conv.user_id === ctx.userId) return conv; if ( ctx.visitorToken && conv.visitor_token === ctx.visitorToken && conv.user_id == null ) { return conv; } throw new Error('Forbidden'); } export async function getOrCreateConversation(ctx: SupportAccessContext) { if (ctx.userId) { let conv = await repo.findActiveConversationForUser(ctx.userId); if (!conv && ctx.visitorToken) { const visitorConv = await repo.findActiveConversationForVisitor(ctx.visitorToken); if (visitorConv && !visitorConv.user_id) { conv = await repo.attachVisitorConversationToUser(visitorConv.id, ctx.userId); } } if (!conv) { conv = await repo.createConversation({ userId: ctx.userId }); } return mapConversation(conv); } if (!ctx.visitorToken) { throw new Error('Visitor token is required for anonymous support'); } let conv = await repo.findActiveConversationForVisitor(ctx.visitorToken); if (!conv) { conv = await repo.createConversation({ visitorToken: ctx.visitorToken }); } return mapConversation(conv); } export async function listUserConversations(ctx: SupportAccessContext) { if (!ctx.userId) { if (!ctx.visitorToken) throw new Error('Not authenticated'); const conv = await repo.findActiveConversationForVisitor(ctx.visitorToken); return conv ? [mapConversation(conv)] : []; } const rows = await repo.listConversationsForUser(ctx.userId); return rows.map(mapConversation); } export async function getConversationMessages( conversationId: string, ctx: SupportAccessContext, after?: string ) { await assertConversationAccess(conversationId, ctx); const rows = await repo.listMessages(conversationId, after); const staffIds = rows .filter((m) => m.sender_type === 'staff' && m.sender_user_id) .map((m) => m.sender_user_id!); const staffNames = new Map(); for (const id of [...new Set(staffIds)]) { const name = await repo.getStaffDisplayName(id); if (name) staffNames.set(id, name); } const readerSide = isStaffRole(ctx.role) ? 'staff' : 'user'; await repo.markMessagesRead(conversationId, readerSide); await repo.resetUnreadCounters(conversationId, readerSide); await publishSupportEvent(conversationId, { type: 'message.read', conversationId, }); const typing = await getTypingIndicators(conversationId); return { messages: rows.map((r) => mapMessage(r, staffNames)), typing, }; } export async function sendMessage( conversationId: string, ctx: SupportAccessContext, input: { body?: string; attachmentUrl?: string; attachmentName?: string; attachmentMime?: string } ) { const conv = await assertConversationAccess(conversationId, ctx); const body = input.body?.trim() ?? null; if (!body && !input.attachmentUrl) { throw new Error('Message body or attachment is required'); } let senderType: SupportSenderType; let senderUserId: string | null = null; if (isStaffRole(ctx.role)) { senderType = 'staff'; senderUserId = ctx.userId ?? null; } else if (ctx.userId && conv.user_id === ctx.userId) { senderType = 'user'; senderUserId = ctx.userId; } else { senderType = 'visitor'; } const msg = await repo.createMessage({ conversationId, senderType, senderUserId, body, attachmentUrl: input.attachmentUrl ?? null, attachmentName: input.attachmentName ?? null, attachmentMime: input.attachmentMime ?? null, }); const preview = previewForMessage(body, input.attachmentName ?? null); const staffSent = senderType === 'staff'; await repo.touchConversationLastMessage( conversationId, preview, staffSent, !staffSent ); if (conv.status === 'resolved' || conv.status === 'closed') { await repo.updateConversation(conversationId, { status: 'open' }); } await publishSupportEvent(conversationId, { type: 'message.new', conversationId, messageId: msg.id, message: mapMessage(msg) as unknown as Record, }); return mapMessage(msg); } export async function setTyping( conversationId: string, ctx: SupportAccessContext, active: boolean ) { await assertConversationAccess(conversationId, ctx); const party = isStaffRole(ctx.role) ? 'staff' : 'user'; await setTypingIndicator(conversationId, party, active); return { ok: true }; } export async function listAdminConversations(filters: { status?: string; assignedTo?: string | null; search?: string; page?: number; pageSize?: number; }) { const pageSize = Math.min(filters.pageSize ?? 30, 100); const page = Math.max(filters.page ?? 1, 1); const { rows, total } = await repo.listConversationsAdmin({ status: filters.status as repo.ConversationListFilters['status'], assignedTo: filters.assignedTo, search: filters.search, limit: pageSize, offset: (page - 1) * pageSize, }); return { items: rows.map(mapConversation), total, page, pageSize, totalPages: Math.ceil(total / pageSize) || 1, }; } export async function getAdminConversationDetail(conversationId: string) { const conv = await repo.findConversationById(conversationId); if (!conv) throw new Error('Conversation not found'); let userContext = null; if (conv.user_id) { const u = await repo.getUserContextForSupport(conv.user_id); if (u) { userContext = { id: u.id, email: decryptEmail(u.email_encrypted), firstName: u.first_name, lastName: u.last_name, displayName: [u.first_name, u.last_name].filter(Boolean).join(' ').trim() || null, role: u.role_name, emailVerified: u.email_verified, isEnabled: u.is_enabled, createdAt: u.created_at.toISOString(), }; } } return { conversation: mapConversation(conv), user: userContext, }; } export async function updateAdminConversation( conversationId: string, staffUserId: string, patch: { status?: string; assignedTo?: string | null; subject?: string; } ) { const conv = await repo.findConversationById(conversationId); if (!conv) throw new Error('Conversation not found'); const updated = await repo.updateConversation(conversationId, { status: patch.status as SupportConversationRow['status'], assignedTo: patch.assignedTo !== undefined ? patch.assignedTo : conv.assigned_to ?? (patch.status === 'open' ? staffUserId : conv.assigned_to), subject: patch.subject, }); await publishSupportEvent(conversationId, { type: 'conversation.updated', conversationId, }); return mapConversation(updated!); } export async function getStaffUnreadCount(): Promise { return repo.countUnreadStaffInbox(); } export function resolveUploadPath(storedName: string): string { const base = path.resolve(process.cwd(), 'data', 'support-uploads'); const safe = path.basename(storedName); return path.join(base, safe); } export function ensureUploadDir(): string { const dir = path.resolve(process.cwd(), 'data', 'support-uploads'); fs.mkdirSync(dir, { recursive: true }); return dir; } export function publicAttachmentUrl(storedName: string): string { return `/api/v1/support/files/${encodeURIComponent(storedName)}`; } /** Links all anonymous visitor conversations to a newly registered or logged-in user. */ export async function mergeVisitorSupportForUser( userId: string, visitorToken: string | null | undefined ): Promise { if (!visitorToken || visitorToken.length < 16) return 0; const count = await repo.mergeAllVisitorConversationsToUser(visitorToken, userId); if (count > 0) { const rows = await repo.listConversationsForUser(userId, count); for (const row of rows.slice(0, count)) { await publishSupportEvent(row.id, { type: 'conversation.updated', conversationId: row.id, }); } } return count; }