/** * GET /api/chats/[chatId] - Busca detalhes de um chat específico */ import { type NextRequest, NextResponse } from "next/server"; import { requireAuth } from "@/lib/auth/middleware"; import { connectMongoDB } from "@/lib/mongodb/connection"; import { Chat } from "@/lib/mongodb/models/Chat"; import { secureLogger } from "@/lib/secure-logger"; export async function GET( request: NextRequest, { params }: { params: Promise<{ chatId: string }> }, ) { try { const authResult = await requireAuth(request); if (authResult instanceof NextResponse) return authResult; const auth = authResult; const { chatId } = await params; await connectMongoDB(); // Buscar chat const chat = await Chat.findOne({ chat_id: chatId }); if (!chat) { return NextResponse.json( { success: false, error: "Chat não encontrado" }, { status: 404 }, ); } // Verificar se o usuário pertence ao chat if (chat.buyer_id !== auth.userId && chat.seller_id !== auth.userId) { return NextResponse.json( { success: false, error: "Você não tem permissão para acessar este chat", }, { status: 403 }, ); } return NextResponse.json( { success: true, chat: { chat_id: chat.chat_id, listing_id: chat.listing_id, buyer_id: chat.buyer_id, seller_id: chat.seller_id, created_at: chat.created_at.toISOString(), updated_at: chat.updated_at.toISOString(), last_message_at: chat.last_message_at?.toISOString() || null, last_message_preview: chat.last_message_preview, buyer_unread_count: chat.buyer_unread_count, seller_unread_count: chat.seller_unread_count, is_active: chat.is_active, listing_cache: chat.listing_cache, buyer_cache: chat.buyer_cache, seller_cache: chat.seller_cache, }, }, { status: 200 }, ); } catch (error) { secureLogger.error("❌ Erro ao buscar chat", { error: error instanceof Error ? error.message : "Erro desconhecido", stack: error instanceof Error ? error.stack : undefined, }); return NextResponse.json( { success: false, error: "Erro ao buscar chat" }, { status: 500 }, ); } }