/** * GET /api/chats/unread-count * Retorna contagem de usuários únicos com mensagens não vistas */ 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) { try { const authResult = await requireAuth(request); if (authResult instanceof NextResponse) return authResult; const auth = authResult; await connectMongoDB(); // Buscar todos os chats do usuário const chats = await Chat.find({ $or: [{ buyer_id: auth.userId }, { seller_id: auth.userId }], is_active: true, }); // Calcular contagem de usuários únicos com mensagens não vistas const uniqueUsersWithUnread = new Set(); chats.forEach((chat) => { let unreadCount = 0; let otherUserId: number; if (chat.buyer_id === auth.userId) { unreadCount = chat.buyer_unread_count; otherUserId = chat.seller_id; } else { unreadCount = chat.seller_unread_count; otherUserId = chat.buyer_id; } // Se há mensagens não vistas, adicionar o outro usuário ao Set if (unreadCount > 0) { uniqueUsersWithUnread.add(otherUserId); } }); return NextResponse.json( { success: true, count: uniqueUsersWithUnread.size, totalUnreadMessages: chats.reduce((total, chat) => { if (chat.buyer_id === auth.userId) { return total + chat.buyer_unread_count; } return total + chat.seller_unread_count; }, 0), }, { status: 200 }, ); } catch (error) { secureLogger.error("❌ Erro ao buscar contagem de chats não lidos", { error: error instanceof Error ? error.message : "Erro desconhecido", stack: error instanceof Error ? error.stack : undefined, }); return NextResponse.json( { success: false, error: "Erro ao buscar contagem" }, { status: 500 }, ); } }