import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { chatOnce } from "@/lib/ollama";

export async function POST(
  _req: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const session = await auth();
  if (!session?.user?.id) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;
  const chat = await prisma.chat.findUnique({
    where: { id },
    include: { messages: { orderBy: { createdAt: "asc" }, take: 4 } },
  });
  if (!chat || chat.userId !== session.user.id)
    return NextResponse.json({ error: "Not found" }, { status: 404 });

  const user = await prisma.user.findUnique({ where: { id: session.user.id } });
  if (!user) return NextResponse.json({ error: "User not found" }, { status: 404 });

  const transcript = chat.messages
    .map((m) => `${m.role.toUpperCase()}: ${m.content.slice(0, 500)}`)
    .join("\n");

  try {
    const raw = await chatOnce(user.ollamaUrl, {
      model: chat.model,
      messages: [
        {
          role: "system",
          content:
            "Generate a 3-5 word title for the following conversation. Reply with ONLY the title, no quotes, no punctuation at the end.",
        },
        { role: "user", content: transcript },
      ],
      options: { temperature: 0.3 },
    });
    const title = raw
      .replace(/<think>[\s\S]*?<\/think>/g, "")
      .replace(/["'.]/g, "")
      .trim()
      .split("\n")[0]
      ?.slice(0, 80) || "New chat";

    const updated = await prisma.chat.update({ where: { id }, data: { title } });
    return NextResponse.json({ chat: updated });
  } catch (e) {
    return NextResponse.json(
      { error: e instanceof Error ? e.message : "Title generation failed" },
      { status: 502 },
    );
  }
}
