import { db } from "@/lib/db";
import { NextResponse } from "next/server";

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { conversationId, role, content, audioUrl } = body;

    if (!conversationId || !role || !content) {
      return NextResponse.json(
        { error: "conversationId, role, and content are required" },
        { status: 400 }
      );
    }

    const message = await db.message.create({
      data: {
        conversationId,
        role,
        content,
        audioUrl: audioUrl || null,
      },
    });

    // Update conversation timestamp
    await db.conversation.update({
      where: { id: conversationId },
      data: { updatedAt: new Date() },
    });

    // Auto-title: use first user message as title
    if (role === "user") {
      const existingMessages = await db.message.count({
        where: { conversationId },
      });
      if (existingMessages === 1) {
        const title = content.slice(0, 50) + (content.length > 50 ? "..." : "");
        await db.conversation.update({
          where: { id: conversationId },
          data: { title },
        });
      }
    }

    return NextResponse.json(message);
  } catch (error) {
    console.error("Failed to save message:", error);
    return NextResponse.json(
      { error: "Failed to save message" },
      { status: 500 }
    );
  }
}
