import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { pushToConversation } from "@/lib/realtimeStore";

/**
 * POST /api/messages/typing
 *
 * Broadcasts a typing indicator to other participants in a conversation.
 * Body: { conversationId: string, isTyping: boolean }
 */
export async function POST(req: Request) {
    const user = await getCurrentUser();
    if (!user) {
        return new Response("Unauthorized", { status: 401 });
    }

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

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

        // Verify user is a participant
        const membership =
            await prisma.conversationParticipant.findUnique({
                where: {
                    conversation_id_user_id: {
                        conversation_id: conversationId,
                        user_id: user.id,
                    },
                },
            });

        if (!membership || membership.left_at) {
            return Response.json(
                { error: "Not a participant" },
                { status: 403 }
            );
        }

        // Broadcast typing event to other participants
        pushToConversation(
            conversationId,
            {
                type: isTyping ? "typing_start" : "typing_stop",
                data: {
                    userId: user.id,
                    userName: user.name || "Someone",
                    conversationId,
                },
                conversationId,
                timestamp: new Date().toISOString(),
            },
            user.id // exclude sender
        );

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