import { NextRequest, NextResponse } from 'next/server'; import { db } from '@/lib/db'; import { requireAuth } from '@/lib/auth'; import { getErrorMessage } from '@/lib/errors'; // Send a message to a conversation export async function POST( 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; const { content } = await request.json(); if (!content || content.trim().length === 0) { return NextResponse.json({ error: 'Message content is required' }, { status: 400 }); } // 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 }); } // Create message const { rows: msgRows } = await db.query( 'INSERT INTO direct_messages (conversation_id, sender_id, content) VALUES ($1, $2, $3) RETURNING *', [id, user.id, content] ); // Update conversation updated_at await db.query( 'UPDATE conversations SET updated_at = NOW() WHERE id = $1', [id] ); // Get sender info const { rows: userRows } = await db.query( 'SELECT id, username, first_name, last_name, role FROM users WHERE id = $1', [user.id] ); return NextResponse.json({ message: { ...msgRows[0], sender_id: user.id, username: userRows[0].username, first_name: userRows[0].first_name, last_name: userRows[0].last_name, role: userRows[0].role } }); } catch (error) { console.error('Send message error:', error); return NextResponse.json( { error: getErrorMessage(error, 'Failed to send message') }, { status: 500 } ); } }