import { NextRequest, NextResponse } from 'next/server'; import { db } from '@/lib/db'; import { requireAuth } from '@/lib/auth'; import { getErrorMessage } from '@/lib/errors'; // Get messages for a conversation export async function GET( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const user = await requireAuth(); if (!user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const { id } = await params; // Verify user is participant const { rows: participants } = await db.query( 'SELECT * FROM conversation_participants WHERE conversation_id = $1 AND user_id = $2', [id, user.id] ); if (participants.length === 0) { return NextResponse.json({ error: 'Not authorized for this conversation' }, { status: 403 }); } // Get all messages with sender info const { rows: messages } = await db.query(` SELECT dm.id, dm.content, dm.created_at, u.id as sender_id, u.username, u.first_name, u.last_name, u.role FROM direct_messages dm JOIN users u ON dm.sender_id = u.id WHERE dm.conversation_id = $1 ORDER BY dm.created_at ASC `, [id]); // Get conversation details with participants const { rows: convRows } = await db.query(` SELECT c.id, c.subject, c.created_at, c.updated_at FROM conversations c WHERE c.id = $1 `, [id]); const { rows: participantRows } = await db.query(` SELECT u.id, u.username, u.first_name, u.last_name, u.role FROM conversation_participants cp JOIN users u ON cp.user_id = u.id WHERE cp.conversation_id = $1 `, [id]); return NextResponse.json({ conversation: convRows[0], participants: participantRows, messages }); } catch (error) { console.error('Get messages error:', error); return NextResponse.json( { error: getErrorMessage(error, 'Failed to get messages') }, { status: 500 } ); } }