import { pushToConversation } from "@/lib/realtimeStore";

/**
 * POST /api/messages/push
 *
 * Internal endpoint used by server actions to push real-time events.
 * This runs in the same bundle/process as the SSE stream route,
 * ensuring it has access to the same in-memory connection pool.
 *
 * Body: { conversationId, event, excludeUserId? }
 */
export async function POST(req: Request) {
    // Simple shared-secret check to prevent external abuse
    const authHeader = req.headers.get("x-internal-secret");
    if (authHeader !== (process.env.INTERNAL_API_SECRET || "internal-push-secret-key")) {
        return Response.json({ error: "Forbidden" }, { status: 403 });
    }

    try {
        const { conversationId, event, excludeUserId } = await req.json();

        if (!conversationId || !event) {
            return Response.json(
                { error: "conversationId and event required" },
                { status: 400 }
            );
        }

        pushToConversation(conversationId, event, excludeUserId);

        return Response.json({ success: true });
    } catch (error) {
        console.error("Push API Error:", error);
        return Response.json(
            { error: "Invalid request" },
            { status: 400 }
        );
    }
}
