73 lines
2.0 KiB
TypeScript
73 lines
2.0 KiB
TypeScript
/**
|
|
* POST /api/chats/mark-all-read
|
|
* Marca todas as mensagens de todos os chats do usuário como lidas
|
|
*/
|
|
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 { Message } from "@/lib/mongodb/models/Message";
|
|
import { secureLogger } from "@/lib/secure-logger";
|
|
|
|
export async function POST(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,
|
|
});
|
|
|
|
// Para cada chat, marcar mensagens não lidas como lidas
|
|
const updatePromises = chats.map(async (chat) => {
|
|
const chatId = chat.chat_id;
|
|
|
|
// Marcar mensagens como lidas
|
|
await Message.updateMany(
|
|
{
|
|
chat_id: chatId,
|
|
sender_id: { $ne: auth.userId },
|
|
read_at: null,
|
|
},
|
|
{
|
|
$set: { read_at: new Date() },
|
|
},
|
|
);
|
|
|
|
// Zerar contador de não lidas
|
|
if (chat.buyer_id === auth.userId) {
|
|
chat.buyer_unread_count = 0;
|
|
} else {
|
|
chat.seller_unread_count = 0;
|
|
}
|
|
|
|
return chat.save();
|
|
});
|
|
|
|
await Promise.all(updatePromises);
|
|
|
|
return NextResponse.json(
|
|
{
|
|
success: true,
|
|
message: "Todos os chats marcados como lidos",
|
|
},
|
|
{ status: 200 },
|
|
);
|
|
} catch (error) {
|
|
secureLogger.error("❌ Erro ao marcar chats como lidos", {
|
|
error: error instanceof Error ? error.message : "Erro desconhecido",
|
|
stack: error instanceof Error ? error.stack : undefined,
|
|
});
|
|
|
|
return NextResponse.json(
|
|
{ success: false, error: "Erro ao marcar como lido" },
|
|
{ status: 500 },
|
|
);
|
|
}
|
|
}
|